开发者社区> 问答> 正文

c++ 临时变量问题?

#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?

展开
收起
杨冬芳 2016-05-30 16:48:46 2360 0
1 条回答
写回答
取消 提交回答
  • IT从业

    因为前者,“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语句结束时立即被销毁。这种函数总是返回一个悬垂引用。

    2019-07-17 19:20:45
    赞同 展开评论 打赏
问答分类:
C++
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载