Move copy constructor
Grammar:
ClassName (classname&&);
Objective:
Used to steal resources (such as memory) in "temporary variables"
Temporary variables are set to constant form by the compiler and cannot be stolen using the copy constructor ("Stealing" is a change to the original object, violating the constant limit)
The move constructor, which is defined based on rvalue reference, supports accepting temporary variables, which can steal resources from temporary variables;
#include <iostream>using namespacestd;classtest{ Public: int*buf;//Only for demoTest () {buf=New int(3); cout<<"Test (): This->[email protected]"<< Hex << buf <<Endl; } ~Test () {cout<<"~test (): This->[email protected]"<< Hex << buf <<Endl; if(BUF)Deletebuf; } Test (Consttest& t): buf (New int(*t.buf)) {cout<<"Test (const test&) called.this->[email protected]"<< Hex << buf <<Endl; } Test (Test&&t): buf (t.buf) {cout<<"Test (test&&) called.this->[email protected]"<< Hex << buf <<Endl; T.buf=nullptr; }}; Test gettemp () {test tmp; cout<<"gettemp (): [Email protected]"<< Hex << tmp.buf <<Endl; returntmp//returns an object to an unknown name}voidFun (Test t) {cout<<"Fun (Test t): [email protected]"<< Hex << t.buf <<Endl;}intMain () {Test a=gettemp (); cout<<"Main (): [Email protected]"<< Hex << a.buf <<Endl; Fun (a);//Copy Call return 0;}
Note: The compiler optimizes the return value, thus increasing the compilation options and preventing the compiler from optimizing the return value
/*
g++ Wo2.cpp--std=c++11-fno-elide-constructors
*/
C + + Programming Method 3: Moving constructors