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

自定义类右值引用绑定对象:为何引用出域未触发析构?

关于右值引用与析构函数调用的疑问

以下是测试代码:

#include <iostream>

using namespace std;

class Someclass
{
    public:
    
    ~Someclass()
    {
        cout << "Someclass Dtor called" << endl;
    }
};

int main()
{
    Someclass obj;
    
    {
        Someclass&& ref = move(obj);
    }

    // At this point why the dtor is not called ? Because the reference went out of scope
    
    cout << "Ending program" << endl;
    
    return 0;
}

实际输出:

Ending program
Someclass Dtor called

疑问:

为何输出不是如下结果?

Someclass Dtor called
Ending program

当右值引用离开作用域时,难道不应该调用Someclass的析构函数吗?


解答:

核心原因是引用(包括右值引用)本身不是对象,它只是对已有对象的别名:

  • Someclass&& ref = move(obj); 里的ref只是原对象obj的一个右值引用别名,move(obj)并没有转移obj的所有权,只是把obj的类型转换为右值引用类型,原对象obj的生命周期依然由它的定义位置决定——也就是main函数的作用域。
  • 内部代码块结束时,只有右值引用ref本身被销毁,但这只是销毁了"别名",并不会触发原对象obj的析构函数。
  • 只有当main函数执行完毕,obj离开自身作用域时,才会调用Someclass的析构函数,这就是为什么"Someclass Dtor called"会在"Ending program"之后输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:20:10