为什么析构函数被调用两次,而构造函数只被调用一次

Why is the destructor getting called twice but the constructor only once?

本文关键字:调用 构造函数 一次 析构函数 为什么 两次      更新时间:2023-10-16

我的代码是

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

为什么构造函数被调用一次,而析构函数被调用两次?有人能解释一下吗?

void Dowork(CTemp obj)

这里将进行本地复制,从DoWork函数的作用域退出后将进行析构函数,这就是您看到析构函数调用的原因。

实现一个复制构造函数并再次检查:

CTemp(const CTemp& rhs){
        printf("nIn copy cons");
    }

当函数被调用时,它的参数是通过使用隐式复制构造函数创建的。将以下复制构造函数添加到您的类中

CTemp( const CTemp & ){
    printf("nIn ccons");
}

查看关于创建对象的另一条消息