I have posted a similar question before why my local object destroyed twice? but I am confused on other point.
here’s the program:
class AT
{
public:
int a;
AT() { cout<<"construct"<<endl; }
AT(const AT& at) { cout<<"copy"<<endl; }
~AT() { cout<<"destroy"<<endl; }
};
AT func(AT at)
{
return at;
}
AT func2(AT at)
{
at.a = 5;
return at;
}
then I call:
AT at;
func2(func(at));
the output is:
construct
copy
copy
destroy
copy
destroy
destroy
I suppose there would be 4 copy and 4 destroys in output, I am clear in func(at), argument is copied, and return value is copied, and both are destroyed later. But in func2(), it seems the argument is not copied. Does it means: if pass a return value to argument, the argument will not be copied?
Probably some compiler optimization.
At is not created only to be destroyed afterwards.
Instead the argument is of func is used to create the argument of func2 directly as if you had called func2(at);