本文介绍了为什么我的本地对象销毁了两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数返回一个本地对象:
class AT
{
public:
AT(){cout<<construct<< endl; }
AT(const AT& at){cout<<copy<< }
〜AT(){cout };
AT funcAt()
{
AT tmp;
return tmp;
}
...
funcAt();
输出为:
construct
copy
destroy
destroy
我想只有构造和销毁的tmp,所以为什么有复制和另一个破坏?
1
)created: AT tmp
里面的funcAt 2)复制:
return tmp;
因为函数返回一个副本: AT funcAt()
3)destroy - 第一个tmp对象和返回的副本
提示:注意输出中的 copy
)
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;
}
...
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?
解决方案
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 :)
这篇关于为什么我的本地对象销毁了两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!