返回对临时对象的引用
returning reference to temporary object
我在Facebook上看一个视频 奇怪的重复出现的C++错误 在 14:58 在代码中(参见我在这里给出的示例(,他说这是无可救药的破坏。原因是返回对临时对象的引用应该不起作用。
那么为什么它有效呢?
#include <iostream>
#include <map>
using namespace std;
const string& get_default(
const map<string,string>& map,
const string& key,
const string& dflt) {
auto pos = map.find(key);
return (pos != map.end() ?
pos->second : dflt);
}
int main()
{
map<string,string> m;
auto& value = get_default(m,"whatever","this is the default value");
cout << value << endl;
return 0;
}
我理解为什么我不能返回对局部变量的引用(当我尝试打印它时会失败(,但我不能让这段代码失败,我不知道为什么。我检查了谷歌,发现如果将临时对象分配给引用,则临时对象的生存期将延长(这就是它工作的原因? 如果是这样,为什么这段代码被破坏得如此无望?
使用: gcc 7.3.0, c++14
现在使用注释,我可以看到如何使其失败: 谢谢大家:)
int main()
{
map<string,string> m;
auto& value = get_default(m,"whatever","this is the default value"); // const string& value = fails the same way
string a = "some long string";
cout << value << endl;//"some long string" will be printed here (this is how it fails - and shows that it is a mess)
return 0;
}
临时对象的生存期仅在某些上下文中延长。发布的代码中的示例不是这些上下文之一。
int foo() { return 10; }
...
int const& x = foo(); // Life of the temporary is extended.
然而
const int& foo() { return 10; } // Life of the temporary is not extended.
...
int const& x = foo(); // Dangling reference.
您发布的代码类似于
const int& foo(int const& in) { return in; }
...
int const& x = foo(10);
在这里,引用仅在foo
内有效。一旦foo
返回,对象将不再处于活动状态,并且引用将变为悬空引用。
相关文章:
- 为什么当我们有常量引用时创建临时对象?
- 返回对临时对象的引用
- 通过引用传递临时对象
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 对临时对象的Const引用不会延长其生存期
- 为什么引用类型在使用临时对象访问时是左值
- 取消引用临时对象上的运算符
- 常量引用函数参数:是否可以禁止临时对象?
- 为什么临时对象可以绑定到常量引用?
- 为什么常量引用不能延长通过函数传递的临时对象的生存期?
- 使用常量引用延长临时对象的寿命
- 从函数返回引用是否会导致在使用'auto'时创建新的临时对象?
- 关于将临时对象传递给常量引用
- 将临时对象绑定到常量引用
- C++17:是编译器为(静态存储持续时间)const引用绑定创建的可修改的临时对象(和存储)
- 返回对本地临时对象 C++ 的引用
- 模板类型推导警告返回对本地临时对象的引用
- 为什么不对临时对象进行非常量引用
- 为什么我们可以非常量引用临时对象并延长其生命周期
- C++悬空的常量引用临时对象