使用对按值返回的值的const引用
Using a const reference to a returned by value value
查看以下示例:
string foo(int i) {
string a;
... Process i to build a ...
return a;
}
void bar(int j) {
const string& b = foo(j);
cout << b;
}
我知道RVO和NRVO,但我认为为了做到这一点,我需要将bar写如下:
void bar(int j) {
string b = foo(j);
cout << b;
}
两个版本似乎都有效,我相信性能相同。使用第一个版本(带有const引用)安全吗?
谢谢。
为常量引用指定临时值是完全有效的。临时对象将一直存在,直到引用超出范围。
虽然它在您的示例中没有意义,但此功能通常用于函数参数:
string foo(int i) {
string a;
// ...
return a;
}
void bar(const string& str) {
// ...
}
void buzz() {
// We can safely call bar() with the temporary string returned by foo():
bar(foo(42));
}
在这种简单的情况下是安全的。然而,添加代码很容易,这会使它变得不安全,而且任何了解C++的人都会感到困惑:为什么你需要在这里引用?没有理由这么做,而且通常应该避免这样的代码。
允许const引用绑定到临时的,临时的生存时间将扩展到const引用的生存时间。所以,是的,它是安全的使用。
使用第一个版本(带有const引用)安全吗?
是的。将临时引用绑定到常量引用会将临时引用的生存期延长到引用本身的生存期,这就是声明引用的范围:
void f()
{
const string& a = foo(10);
//some work with a
{
const string& b = foo(20);
//some work with b
} //<----- b gets destroyed here, so the temporary also gets destroyed!
//some more work with a
} //<----- a gets destroyed here, so the temporary associated
//with it also gets destroyed!
Herb Sutter在他的文章中详细解释了这一点:
"最重要常数"的候选者
它值得一读。必须读取。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 对临时对象的Const引用不会延长其生存期
- 对 const 引用参数使用默认值会导致崩溃
- 在运算符重载中使用带有 const 引用的 friend 函数
- C++通过 const 引用传递时不调用派生类函数
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 为什么要返回对小类成员的 const 引用?
- C - 最好将枚举类作为值或const引用
- RVO:返回由值传递的值,即使显式分配给 const 引用也是如此
- const引用与可变成员的对象
- 每当传递lvalue时,每当通过rvalue传递时,将const引用存储
- 对类成员而不是 getter 的 Const 引用
- 从类型 'Matrix&' 的右值初始化 类型的非 const 引用无效 'Matrix'
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- STD ::配对的const引用如何工作
- 为什么我的C 函数拒绝返回const引用