Possible Duplicate:
What are copy elision and return value optimization?
why isn’t the copy constructor called
Why in the following code both gcc and clang don't call copy constructor of A class even one time (there is only one object created as destructor is called only one time).
class A
{
public:
explicit A()
{
std::cout << "A()" << std::endl;
}
A(const A& toCp)
{
std::cout << "A(const A&)" << std::endl;
}
~A()
{
std::cout << "~A()" << std::endl;
}
A& operator=(const A& toCp)
{
std::cout << "A::operator=" << std::endl;
}
};
A fun()
{
A x;
std::cout << "fun" << std::endl;
return x;
}
int main()
{
A u = fun();
return 0;
}
Printout of this code is:
A()
fun
~A()
I thought it copy constructor should be called 2 times (one for returning value and one in line A u = fun(7);
I used gcc and clang with -O0 for this code.
Any ideas?