从函数返回引用与临时绑定到常量引用
Return reference from function vs binding temporary to const ref
我是对的,这个(取自这个GotW(:
string f() { return "abc"; }
void g() {
const string& s = f();
cout << s << endl; // can we still use the "temporary" object?
}
完全没问题,而这根本不行:
const string& foo() { string x{"abc"}; return x; }
void bar() {
const string& y = foo();
}
?
为什么不同?可以说"temporay 的生命周期不会在函数调用中延长(即使绑定到 const 引用("?或者什么是解释,为什么第一个可以,但第二个不行?
第一个很好,因为返回值(临时值(直接绑定到对 const 的引用,然后临时值的生存期延长到引用的生存期。
请注意,在第两种情况下没有临时的,x
是一个局部变量,当退出函数时将被销毁,那么该函数将始终返回一个悬空的引用;该引用用于初始化y
但没有任何变化,y
也将是一个悬空的引用。
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 将常量指针引用绑定到非常量指针
- 运行时错误:引用绑定到类型为"int"的空指针
- 模板允许左值与右值引用绑定
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 无法将类型"T&"的非常量左值引用绑定到类型"T"的右值 t++ std::atomic<T>
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 将引用绑定到指针的语法是什么?(各种)
- 为什么我不能将常量左值引用绑定到返回 T&&&的函数?
- 为什么 VS 无法将右值引用绑定到指针?
- 出于什么原因,有必要将常量左值引用绑定到右值?
- 为什么此右值引用绑定到左值?
- 使用“void*”将右值引用绑定到左值
- 排序时引用绑定到 'value_type' 类型的 null 指针
- 无法将类型为"类名 &"的非常量左值引用绑定到类型为"类名"的右值
- 引用绑定和复制构造函数/移动构造函数
- 将引用绑定到类型的值会删除限定符 MULTISET
- 无法将类型"int&"的非常量左值引用绑定到类型为"int"的右值
- 多态变体,并将一种类型的引用绑定到另一种类型的引用
- C++17:是编译器为(静态存储持续时间)const引用绑定创建的可修改的临时对象(和存储)