右值引用绑定的自定义类的右值的生命周期

问题描述 投票:0回答:1
#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;
}

上面的代码输出如下:

节目结束

某个班主任打来电话

但是我的疑问是为什么输出不是这个?

某个班主任打来电话

节目结束

当引用超出范围时,不应该调用Someclass的dtor吗?

c++ move rvalue-reference
1个回答
0
投票

当引用超出范围时,不应该调用 Someclass 的 dtor 吗?

不。 (l-or-r)引用是现有对象的别名或替代名称。它提供了一种通过另一个名称访问对象的方法。它不拥有该对象。

因此当这一行:

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

rvalue

ref
超出范围,唯一的别名是超出范围,而不是实际对象。

© www.soinside.com 2019 - 2024. All rights reserved.