If I have a class A (which returns an object by value ), and two functions f() and g() having difference in just their return variables :
class A
{
public:
A () { cout<<"constructor, "; }
A (const A& ) { cout<<"copy-constructor, "; }
A& operator = (const A& ) { cout<<"assignment, "; }
~A () { cout<<"destructor, "; }
};
const A f(A x)
{A y; cout<<"f, "; return y;}
const A g(A x)
{A y; cout<<"g, "; return x;}
main()
{
A a;
A b = f(a);
A c = g(a);
}
Now when I execute the line A b = f(a);
, it outputs:
copy-constructor, constructor, f, destructor
, which is fine assuming that object y in f() is created directly at the destination i.e at the memory location of object b, and no temporaries involved.
While when I execute the line A c = g(a);
, it outputs:
copy-constructor, constructor, g, copy-constructor, destructor, destructor,
.
So the question is why in the case of g() cant the object be directly created at memory location of c, the way it happened while calling f() ? Why it calls an additional copy-constructor ( which I presume is because of the involvement of temporary ) in the 2nd case ?