If I have a class A (which returns an object by value), and the two functions f () and g () have a difference only in 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 understands perfectly well that the object y in f () is created directly at the ie destination in the memory cell of object b and the temporary ones are not involved.
While I execute the line A c = g(a);, it produces:
copy-constructor, constructor, g, copy-constructor, destructor, destructor,.
So, the question is why, in the case of g (), it is impossible for the object to be directly created in memory cell c, as happened when f () was called? Why does it call an additional constructor instance (which, I believe, is due to the participation of a temporary one) in the second case?