First look at a question as follows:
a Test () { A A1 (2); << &a1 << std::endl; return A1;}
A a2 = Test ();
For the above code, the next procedure is probably explained.
The A1 object is constructed in the test () function, and when returned, constructs a temporary object and uses a for copy construction. When a a2 = Test () is, A2 uses a temporary object for the copy construction, that is, a total of 2 copies of the construction, 1 times the constructor;
But when using code testing, the results are not the same as imagined.
#include <iostream>classa{ Public: A (inti): A (i) {std::cout<<"construct"<< I <<Std::endl; } ~A () {std::cout<<"des constrcut"<< a <<Std::endl; } A (Consta&a) {std::cout<<"Copy constrcut"<<Std::endl; This->a =A.A; } A&operator=(Consta&b) {std::cout<<"Assign Operation"<<Std::endl; This->a =B.A; return* This; } Public: intA;}; A test () {A A (2); Std::cout<< &a <<Std::endl; returnA;}intMain () {a A=test (); Std::cout<< &a <<Std::endl; return 0;}
g++ Test.cpp-o test, at run time, enter as follows.
The result is that the constructor executes only once, and the copy constructor is not executed, and the object address in the test () function body is the same as the object address in main ().
The query found that the original compiler will automatically perform a value return optimization, that is, Rvo. Rvo will pass the address of the A object to the test function, and the test function modifies the A object directly, avoiding the copy operation. Wikipedia has a detailed description: Http://en.wikipedia.org/wiki/Return_value_optimization.
Finally, the GNU compiler can turn off Rvo with the-fno-elide-constructors option. g++ test.cpp-fno-elide-constructors-o test. The results of the operation are as follows.
The approximate process is as follows:
The test () function object A calls the constructor, returns the temporary object copy construct, and then the object in the function is destructor.
Then the main () function object A copies the temporary objects and then destructors the temporary objects.
Finally, the destructor of the object A.
C + + Return object value