c++ - 引用临时与指向临时及其生命周期的指针

标签 c++ pointers reference lifetime temporary-objects

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

在我的例子中,临时对象是从函数返回的,我想了解临时对象的 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;

}

最佳答案

只有绑定(bind)到 const 引用的临时对象的生命周期才会延长,除了绑定(bind)到函数返回的 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
}

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

关于c++ - 引用临时与指向临时及其生命周期的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103262/

相关文章:

C++ - 直接插入 std::map 而不使用赋值运算符

c++ - 了解引用与指针。为什么这行得通?

jquery - 允许用户从 5 个不同的圣经版本中选择一个来查看引用资料。实现这一目标的最佳方法是什么?隐藏CSS类? Ajax ?

c++ - 如何查看网络流(http)中的视频?

c++ - 如何在不等待新数据到达的情况下使用 boost::asio 的 async_read_some() 读取所有可用数据?

c++ - OpenCV 3.1.0 : Save and load trained SVMs

c - 插入二叉树时出现错误?

更改 C 中结构的变量

c++ - 对匿名右值的引用已损坏

通过引用的 Java 类字段?