我知道返回的局部变量不应按值传递。但是我不明白为什么一个有效,而另一个无效。
数字1
void hello(const string& s)
{
cout << "s";
}
int main()
{
hello("Hello World");
return 0;
}
数字2
const string& returnHello()
{
return "hello world";
}
int main()
{
const string& hh = returnHello();
cout << hh << endl;
return 0;
}
数字2给出了细分错误。
那是为什么?据我了解,如果我在const中返回对临时对象的引用,那应该延长该临时对象的寿命,不是吗?
有人可以帮助我理解为什么一个有效而另一个无效吗?