c++ - 引用的生命周期是否延长?

标签 c++ reference lifetime

我想将引用传递给函数。如我所料,此代码不起作用:

struct A {
};

void foo(A& a) {
    // do something with a
}

int main(int, char**) {
    foo(A());
}

我得到编译错误

invalid initialization of non-const reference of type A& from an rvalue of type A

但是当我像下面那样将方法 A& ref() 添加到 A 并在传递之前调用它时,似乎我可以使用 a。调试时,调用foo()A对象被销毁:

struct A {
    A& ref() {
        return *this;
    }
};

void foo(A& a) {
    // do something with a
}

int main(int, char**) {
    foo(A().ref());
}

这是符合标准的有效代码吗?调用 ref() 是否会神奇地延长对象的生命周期,直到 foo() 返回?

最佳答案

您的代码完全有效。

在这一行

foo(A().ref());

临时 A 的实例一直存在到语句结束 (;)。

这就是为什么将 ref() 返回的 A& 传递给 foo 是安全的(只要 foo不存储它)。

ref() 本身不会延长任何生命周期,但它通过返回一个左值引用来提供帮助。

foo(A()); 的情况下会发生什么?这里临时作为右值传递。而在 C++ 中,右值不会绑定(bind)到非 const 左值引用(即使在 C++11 中,右值 reference 也不会绑定(bind)到非 const 左值引用)。

从此Visual C++ blog article about rvalue references :

... C++ doesn't want you to accidentally modify temporaries, but directly calling a non-const member function on a modifiable rvalue is explicit, so it's allowed ...

关于c++ - 引用的生命周期是否延长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438179/

相关文章:

C++ 字符数组作用域

c++ - 如何解决 "error LNK2019: unresolved external symbol"?

node.js - Node js 导出变量维护引用 - 按引用传递?

rust - Rust生命周期子类型不适用于Cell

c++ - 如何处理返回指针的生命周期?

C++11绑定(bind): difference between using and not-using placeholder

reference - 开发术语和定义引用

c++ - const 引用的内存位置

rust - 如何在 Rust 中使用 sha256 散列 sha256 的输出

c++ - 在主要 C/C++ 编译器生成的代码中注册分配规则