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.
The reason the copy constructor is not called is because the copy constructor itself is a function with one parameter. You didn't call such function,so it didn't execute.
When is a Copy Constructor Called in C++? A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object.
In C++ that statement makes a copy of the object's state. In Java it simply copies the reference. The object's state is not copied so implicitly calling the copy constructor makes no sense. And that's all there is to it really.
And there are 4 calls to copy constructor in f function. 1) u is passed by value. 2) v is copy-initialized from u . 3) w is copy-initialized from v . 4) w is copied on return.
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:
[...] This elision of copy operations is permitted in the following circumstances (which may be combined to eliminate multiple copies):
[...]
- when a temporary class object that has not been bound to a reference (12.2) would be copied to a class object with the same cv-unqualified type, the copy operation can be omitted by constructing the temporary object directly into the target of the omitted copy
You might use some compiler settings to disable this optimization, like in case of gcc, from the man page:
-fno-elide-constructor
The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.
However, using this makes your code non portable across different compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With