C++的一个问题?

#include <iostream>
#include <string>
using namespace std;

const string & func(const string &s)
{
    return s;
}

int main()
{
    cout<<func("abc")<<endl;
    return 0;
}

程序是能执行的

但是 func() 函数合法吗?我知道进入这个函数会创建一个string临时量,并且被s所引用,但是退出 func() 函数后这个临时量会被程序销毁吗?

不知道函数外使用这个临时量合不合法

阅读 2.2k
2 个回答
但是 func() 函数合法吗?

合法。func 并不知道它参数是否是临时变量。所以维护其生命周期是调用者的责任。

我知道进入这个函数会创建一个string临时量,并且被s所引用,但是退出 func() 函数后这个临时量会被程序销毁吗?

临时变量是在对表达式 cout<<func("abc")<<endl 求值时建立的。那么会在整个表达式求值结束之后(而不是 func 调用完成之后)销毁。所以在 cout 的时候临时变量还在。临时变量销毁的时候输出已经结束了。

class.temporary/4 :

When an implementation introduces a temporary object of a class that has a non-trivial constructor ([class.ctor], [class.copy]), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor ([class.dtor]). Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.
新手上路,请多包涵

合法呀,函数的返回值是一个右值,<<是接受右值的呀

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题