析构函数在c ++中调用两次,但构造函数只调用一次 [英] Destructor getting called twice in c++ but the constructor only once
本文介绍了析构函数在c ++中调用两次,但构造函数只调用一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码是
class CTemp{
public:
CTemp(){
printf("\nIn cons");
}
~CTemp(){
printf("\nIn dest");
}
};
void Dowork(CTemp obj)
{
printf("\nDo work");
}
int main()
{
CTemp * obj = new CTemp();
Dowork(*obj);
delete obj;
return 0;
}
我得到的输出是
In cons
Do work
In dest
In dest
现在为什么构造函数被调用一次,而析构函数被调用两次?有人可以解释一下吗?
Now why does the constructor gets called once but the destructor is called twice?Can someone please explain this ?
谢谢
推荐答案
void Dowork(CTemp obj)
这里将执行local-copy,在退出 DoWork
函数,这就是为什么你看到析构函数调用。
Here local-copy will be done, that will be destruct after exit from scope of DoWork
function, that's why you see destructor-call.
这篇关于析构函数在c ++中调用两次,但构造函数只调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文