Class B{public:b () {cout << constructors << Endl;} B (const b &b) {cout << copy constructor << Endl;} ~b () {cout << "destructor" << Endl;}}; b Play (b b) {return B;}
The main function enters the following code:
{B B1;play (B1);}
Output:
The main function enters the following code:
{B B1; B B2=play (B1);}
Output:
Why are the two graphs the same? I guess it's because B B2=play (B1); This line of code produces a temporary return value variable by copying the constructor, and then B2 calls the move copy constructor?
To do the experiment, add the assignment operator and the move constructor:
<pre name= "code" class= "CPP" >class b{public:b () {cout << "constructors" << Endl;} B (const b &b) {cout << copy constructor << Endl;} B (b &&b) {cout << move constructor << Endl;} b& operator= (const B &b) {cout << assignment operator << endl;if (this = = &b) return *this;return *this;} ~b () {cout << "destructor" << Endl;}}; b Play (b b) {return B;} void Main () {{B B1; B B2 = Play (B1);} cout << "-------------------------" << Endl; {B B1; B b2;b2 = Play (B1);}}
Output:
Remove the Move constructor:
Class B {public : B () { cout << "constructors" << Endl; } B (const b &b) { cout << copy constructor << Endl; } b& operator= (const B &b) { cout << assignment operator << Endl; if (this = = &b) return *this; return *this; } ~b () { cout << "destructor" << Endl; } }; b Play (b b) { return b; } void Main () { { B B1; B B2; B2 = Play (B1); }
Output:
Temporary variables and copy constructors