Possible Duplicate:
Why copy constructor is not called in this case?
Consider the sample program below:
#include <iostream>
using namespace std;
class sample
{
private:
int x;
public:
sample(int a=0) : x(a)
{
cout << "default ctor invoked\n";
}
sample(const sample& obj)
{
cout << "copy ctor invoked\n";
}
};
int main()
{
sample s2 = sample(20); //Line1
sample s3 = 20; //Line2
return 0;
}
In Line1
, first the constructor of sample
class is invoked explicitly
with the argument 20. Then i expected the copy constructor to be invoked to initialize s2.
In Line2, first the constructor of sample
class is invoked implicitly
first with the argument 20. Here also i expected the copy constructor to be invoked to initialize s2.
In both cases, the copy constructor is not invoked? Why is this happening? I believe, there is something wrong with my understanding of the invocation of copy constructor. Could someone correct me where i am going wrong?
This is expected. It's called copy elision.
Your expectation is correct, but they made an exception in C++ (for performance) which allows the compiler to treat your expression as direct initialization of one instance while bypassing the copy constructor.
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