why my local object destroyed twice?
I have a function returning a local object:
class AT
{
public:
AT() { cout<<"construct"<<endl; }
AT(const AT& at) { cout<<"copy"<<endl; }
~AT() { cout<<"destroy"<<endl; }
};
AT funcAt()
{
AT tmp;
return tmp;
}
开发者_如何学Python...
funcAt();
output is:
construct
copy
destroy
destroy
I suppose there are only construct and destroy of "tmp", so why there is copy and another destroy? where is the copied object?
Let's flesh this out a bit:
AT funcAt()
{
AT tmp; [1]
return tmp; [2]
} [3]
...
funcAt(); [4]
[1] create an AT object in tmp
[2] copy tmp into return value
[3] destroy tmp
[4] destroy return value because it is not used
Because it is
1) created: AT tmp
inside funcAt
2) copied: return tmp;
and this is because the function returns a copy: AT funcAt()
3) destroy - the first tmp object, and the returned copy
Hint: note the copy
in the output :)
The reason why is because the copy of tmp
is returned from funcAt
and is not stored anywhere hence C++ destroys it and calls the destructor
tmp
is constructed and destroyed. The same is true for the return value (which is a new object, not just a reference) although here the cop constructor is used. You don't see the return value being used but it's still passed.
The return-value of your function is a separate object (i.e. a copy) to the local object used inside the function.
精彩评论