You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++临时对象销毁时析构函数是否触发?为何代码仅输出两次析构信息?

问题分析与解答

代码示例

class demo{
    private:
    int x;
    public:
    demo(int t):x(t) {cout<<"constructor"<<endl;}
    demo(const demo& t):x(t.x) {cout<<"copy constructor"<<endl;}
    demo& operator=(const int& t){
        x=t;
        cout<<"assignment"<<endl;
    }
    demo& operator=(const demo& t){
        x=t.x;
        cout<<"copy assignment"<<endl;
    }
    ~demo()
    {
        cout<<"deconstruction"<<endl;
    }
};
int main()
{
    demo x=2; // 原以为这里会产生临时对象的析构,总共三次"deconstruction"
    demo y(2);
    y=3;
}

疑问点

运行上述代码后仅输出两次deconstruction,但预期是三次:认为demo x=2等价于demo x = demo(2),临时对象demo(2)销毁时会输出一次析构,加上程序结束时x和y的两次,共三次。同时想确认:C++临时对象销毁时,析构函数是否会被调用?

解答

  1. 为什么只有两次析构?
    这是因为C++标准允许编译器进行**拷贝省略(Copy Elision)**优化。demo x=2;这种写法属于直接初始化的一种,编译器不会先创建临时对象demo(2)再拷贝构造x,而是直接调用demo(int)构造函数初始化x,全程没有临时对象生成,自然也就没有额外的析构调用。最终只有x和y两个对象在程序结束时销毁,输出两次deconstruction。

  2. 临时对象销毁时是否调用析构函数?
    是的,只要临时对象被创建出来,当它的生命周期结束时(比如所在语句执行完毕),编译器一定会调用它的析构函数。只是在你的代码里,编译器通过优化跳过了临时对象的创建,所以看不到对应的析构输出。

内容的提问来源于stack exchange,提问作者Mark_Jing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:42:15