default copy constructor behaviour

obj func ()
{
obj o;
return o;
}
obj y = func (); //Initialization - calls default copy ctor
In the above code, the ctor will be called once and and dtor also.


obj func ()
{
obj o;
return o;
}
obj y;
y = func (); //calls default copy ctor
In the above code, the ctor will be called twice and and dtor also.

Q) Why the behavior of the above two code snippets is different?
Thanks for the repy
Different compilers may do different things with

obj y = func ();

Is this
a. Default ctor followed by assignment?, or
b. Copy ctor, by interpreting the statement as
obj y ( func() );

Aside from this, as Peter87 points, there are also optimizations that can be done
to eliminate/reduce temporaries. The recent C++ 11 has rvalue reference, &&,
to help with this optimization.
Topic archived. No new replies allowed.