返回对临时对象的引用

returning reference to temporary object

本文关键字:引用 临时对象 返回      更新时间:2023-10-16

我在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返回,对象将不再处于活动状态,并且引用将变为悬空引用。