#include <iostream>
#include <string>
using namespace std;
const string& Func()
{
return "123";
}
int main()
{
string s = Func();
cout << s << endl;
return 0;
}
const 引用不是会提升临时变量的生命期吗? 为什么返回函数内的临时变量会报错了? 我对const引用的理解哪里错了吗?
#include <iostream>
#include <string>
using namespace std;
const string& Func(const string& s)
{
return s;
}
int main()
{
string s = Func("123");
cout << s << endl;
return 0;
}
但是这段代码就可以了。 Func函数参数绑定到一个临时变量,然后返回这个临时变量的const引用,就没有问题?
why?
因为前者,“123”是在Func函数的内部,也就是该函数的栈上,出了函数就没有了。
而后者“123”是在main函数的内部Func
函数执行完了,控制流返回到了man
函数还在。
const引用会提高临时变量的生命周期是指,临时变量的生命周期本来只是创建该临时变量的表达式,表达式结束后,被析构,const
引用将其生命周期提升到该函数结束时(如果是全局`const引用变量,那自然就是提升到整个程序的生命周期),函数结束被析构,而并不会将其生命周期提升到函数外部,函数结束时,也会被析构掉的。
const引用其实和右值引用差不多,都是都是将临时变量的生命周期从该表达式提升到函数。
补充一点参考资料
Whenever a reference is bound to a temporary or to a base subobject of a temporary, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:
•a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling reference.
•a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists. (note: such initialization is ill-formed as of DR 1696)
•a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.(until C++14)
•a temporary bound to a reference in the initializer used in a new-expression exists until the end of the full expression containing that new-expression, not as long as the initialized object. If the initialized object outlives the full expression, its reference member becomes a dangling reference.
In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference to which the temporary was bound, does not affect its lifetime.
翻译一下前两段,尤其注意加粗的字:
无论何时一个绑定了一个临时变量或者一个临时变量的基类子对象的引用,临时变量的生命周期被扩展到与引用的生命周期相对应,除了一下几个例外:
一个在函数的return语句中对函数的返回值的临时绑定不会被延展:它会在return语句结束时立即被销毁。这种函数总是返回一个悬垂引用。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。