我有一个返回本地对象的函数:
class AT
{
public:
AT() { cout<<"construct"<<endl; }
AT(const AT& at) { cout<<"copy"<<endl; }
~AT() { cout<<"destroy"<<endl; }
};
AT funcAt()
{
AT tmp;
return tmp;
}
...
funcAt();
输出是:
construct
copy
destroy
destroy
我想“tmp”只有construct和destroy,那为什么有copy和另一个destroy呢?复制的对象在哪里?
最佳答案
让我们充实一下:
AT funcAt()
{
AT tmp; [1]
return tmp; [2]
} [3]
...
funcAt(); [4]
[1]在tmp中创建一个AT对象
[2] 将tmp复制到返回值
[3] 销毁 tmp
[4] 销毁返回值,因为它没有被使用
关于c++ - 为什么我的本地对象被破坏了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6075271/