Possible Duplicate:
Why copy constructor is not called in this case?
In the following code, I constructed three variables, a1, a2 and a3.
There’s a example in C++ Primer p.476:
string empty_copy = string();//copy-initialization
Is there anyone can help me explain
1)why a1 and a2 are not constructed by copy constructor and
2)what’s the difference between initialization a2 in my code and empty_copy in the book?
Thanks so much!
#include<iostream>
using namespace std;
class A{
public:
A(){}
A(int v){}
A(const A&x){
cout<<"copy constructor"<<endl;
}
};
A generateA(){
return A(0);
}
int main(){
cout<<"First:"<<endl;
A a1=generateA();
cout<<"Second:"<<endl;
A a2=A(0);
cout<<"Third:"<<endl;
A a3=a1;
return 0;
}
The out put is (under Visual Studio 2010 in Win7 and g++ in Ubuntu10.10):
First:
Second:
Third:
copy constructor
This is copy elision due to Return value optimization.
Compilers are allowed to optimze away generation of copies by applying such optimizations.
In the above both cases the compiler can eliminate the creation of a temporary object which is created to hold the return value.
Involves a already existing named object
a1which is used for construction ofa3this involves a copy constructor call which the compiler must make and cannot optimize.EDIT: To answer the Q in comment.
You can tell the compiler to not apply this optimization by using the following options during compilation:
For GCC:
For MVSC: