baz = MyClass(); // 移动任务
上面的代码中由fn()返回的对象和由MyClass构造出来的对象都是unnamed,用这样的对象给MyClass赋值或初始化时,并不需要拷贝,因为源对象只有很短的生命周期。
移动构造函数与移动赋值函数的定义形式上与拷贝操作一样,只是将拷贝函数的形参的引用换成右值引用。
MyClass (MyClass&&); // 移动构造函数 MyClass& operator= (MyClass&&); // 移动分配
移动操作对那些需要管理存储空间的类是非常有用的,比如我们下面定义的这个类
// 移动构造函数/赋值 #include <iostream> #include <string> using namespace std; class Example6 { string* ptr; public: Example6 (const string& str) : ptr(new string(str)) {} ~Example6 () {delete ptr;} // 移动构造函数 Example6 (Example6&& x) : ptr(x.ptr) {x.ptr=nullptr;} // 移动任务 Example6& operator= (Example6&& x) { delete ptr; ptr = x.ptr; x.ptr=nullptr; return *this; } // 访问内容: const string& content() const {return *ptr;} // 加成: Example6 operator+(const Example6& rhs) { return Example6(content()+rhs.content()); } }; int main () { Example6 foo ("Exam"); Example6 bar = Example6("ple"); // 移动施工 foo = foo + bar; // 移动分配 cout << "foo's content: " << foo.content() << '\n'; return 0; }