mirror of
https://github.com/changkun/modern-cpp-tutorial.git
synced 2025-12-17 12:44:40 +03:00
prepare for c++17
This commit is contained in:
31
code/3/3.4.cpp
Normal file
31
code/3/3.4.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// 3.4.cpp
|
||||
// c++1x tutorial
|
||||
//
|
||||
// created by changkun at shiyanlou.com
|
||||
//
|
||||
// 移动语义
|
||||
|
||||
#include <iostream>
|
||||
class A {
|
||||
public:
|
||||
int *pointer;
|
||||
A():pointer(new int(1)) { std::cout << "构造" << pointer << std::endl; }
|
||||
A(A& a):pointer(new int(*a.pointer)) { std::cout << "拷贝" << pointer << std::endl; } // 无意义的对象拷贝
|
||||
A(A&& a):pointer(a.pointer) { a.pointer = nullptr;std::cout << "移动" << pointer << std::endl; }
|
||||
~A(){ std::cout << "析构" << pointer << std::endl; delete pointer; }
|
||||
};
|
||||
// 防止编译器优化
|
||||
A return_rvalue(bool test) {
|
||||
A a,b;
|
||||
if(test) return a;
|
||||
else return b;
|
||||
}
|
||||
int main() {
|
||||
A obj = return_rvalue(false);
|
||||
std::cout << "obj:" << std::endl;
|
||||
std::cout << obj.pointer << std::endl;
|
||||
std::cout << *obj.pointer << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user