拷贝赋值移动
#include<iostream> using namespace std; class B { public: B() { cout << "B()被调用" << endl; } B(const B&) { cout << "B的拷贝构造函数被调用" << endl; } B& operator=(const B&) { cout << "B的赋值函数被调用" << endl; return *this; } B(B&&) { cout << "B的移动构造函数被调用" << endl; } B& operator=(B&&) { cout << "B的移动赋值被调用" << endl; return *this; } ~B() { } }; class A { private: string *str; B b; public: A(const string& c = string()) :str(new string(c)){ cout << "构造函数被调用" << endl;} A(const A& another) :str(new string(*another.str)),b(another.b) { cout << "拷贝构造被调用" << endl;} A& operator=(const A& another) { cout << "赋值函数被调用" << endl; b = another.b; string *temp = new string(*another.str); delete str; str = temp; return *this; } A(A&&another) { cout << "移动构造被调用" << endl; str = another.str; another.str = nullptr; b = std::move(another.b); } A& operator=(A&&another) { cout << "移动赋值函数被调用" << endl; if (this!=&another) { delete str; str = another.str; another.str = nullptr; b = std::move(another.b); } return *this; } ~A() { delete str; } }; A foo() { return A(); } int main() { //测试一: A a; A b; b = std::move(a); cout << "-------------" << endl; //测试二 A a1; A b2(std::move(a1)); return 0; }
输出: