【问题标题】:Reference to a temporary vs Pointer to temporary and their lifetime引用临时文件与指向临时文件及其生命周期的指针
【发布时间】:2025-11-30 22:30:01
【问题描述】:

我读过很多关于临时对象生命周期的文章,似乎临时对象的生命周期在某些情况下会延长,而在其他情况下,它是一个悬空对象。

在我的情况下,临时对象是从函数返回的,我想了解临时对象的 const ref 是否保持有效。

代码如下:

class MyClass
{
public:
    std::vector<int> vec{ 1, 2 };

    MyClass()
    {
        cout << "Ctor" << endl;
    }

    MyClass(const MyClass &copy)
    {
        vec = copy.vec;         
        cout << "Copy Ctor" << endl;
    }

    ~MyClass()
    {
        cout << "Dtor" << endl;
    }
};

MyClass access()
{
    MyClass obj;
    obj.vec[0] = 10;
    return obj;
}

int main()
{
    {
        const auto &ret = access();             // calls the copy-ctor and assigns the temporary to reference 'ret'
        auto val = ret.vec[0];
        cout << "By Ref = " << val << endl;     // works fine
    }

    cout << "_____________________________________" << endl;

    {
        const auto *ret = &access();            // temporary is lost 
        auto val = ret->vec[0];                 // program crash
        cout << "By Pointer = " << val << endl; 
    }

    return 0;

}

【问题讨论】:

  • 表达式&amp;access() 格式不正确,因为您不能获取prvalue 的地址。一个实现应该打印一个关于这个的诊断。 (MSVC 默认情况下不会,但它会具有足够高的警告级别。)

标签: c++ pointers reference lifetime temporary-objects


【解决方案1】:

只有绑定到 const 引用的临时对象才能延长其生命周期,但绑定到函数返回的 const 引用除外,例如

const int& f(){int x{42}; return x;}
int main()
{
    const int& bad = f(); // you'll end up with a dangling reference
}

const int& f(const int& x)
{
    return x;
}
int main(){
{
    const int& bad = f(42); // you'll end up (again) with a dangling reference
}

在您的第二种情况下,您有一个指针,因此右侧临时的生命周期不会延长。

【讨论】:

  • 将临时对象绑定到右值引用也会延长临时对象的生命周期,这与绑定到 const 的左值引用的条件相同。
  • @aschepler 是的,不想进入右值引用:)