为什么析构函数被调用两次而构造函数仅被调用一次? [英] Why is the destructor getting called twice but the constructor only once?

查看:254
本文介绍了为什么析构函数被调用两次而构造函数仅被调用一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是

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 get called once but the destructor is called twice? Can someone please explain this?

推荐答案

void Dowork(CTemp obj)

此处将完成本地复制,退出 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.

这篇关于为什么析构函数被调用两次而构造函数仅被调用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆