我想将引用传递给函数。如我所料,此代码不起作用:
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 typeA
但是当我像下面那样将方法 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/