Possible Duplicate:
What are copy elision and return value optimization?
I am having difficulty understanding why in the following piece of code the copy constructor is not called.
#include <iostream>
class Test
{
public:
Test(int){std::cout << "Test()" << std::endl;}
Test(const Test&){std::cout << "Test(const Test&)" << std::endl;}
};
int main()
{
// Test test;
Test test2(Test(3));
return 0;
}
Can someone explain why only the constructor is called and no copy constructor ?
Thanks.
This is called as copy elision.
The compilers are allowed to do this optimization. Though it is not guaranteed by the standard any commercial compiler will perform this optimization whenever it can.
Standard Reference:
C++03 12.8.15:
You might use some compiler settings to disable this optimization, like in case of gcc, from the man page:
However, using this makes your code non portable across different compilers.