其他分享
首页 > 其他分享> > c – 临时绑定到引用参数的默认参数的生命周期是多少?

c – 临时绑定到引用参数的默认参数的生命周期是多少?

作者:互联网

我认为引用只会将临时工具的生命周期延长到引用本身的生命周期,但下面代码片段的输出似乎是矛盾的:

#include <iostream>

struct X{ ~X(){ std::cout << "Goodbye, cruel world!\n"; } };

X const& f(X const& x = X()){
  std::cout << "Inside f()\n";
  return x;
}

void g(X const& x){
  std::cout << "Inside g()\n";
}

int main(){
  g(f());
}

Live example.输出:

Inside f()
Inside g()
Goodbye, cruel world!

所以看起来临时在g()被调用后被破坏……是什么给出的?

解决方法:

标准在§12.2[class.temporary]中的特殊情况下处理此问题:

p4 There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. […]

p5 The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

  • A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.

该标准还有一个关于全表达式的便利说明,以及关于§1.9[intro.execution] p11中默认参数的子表达式的评估:

[ Note: The evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default arguments (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument. —end note ]

标签:temporary-objects,c,language-lawyer,lifetime
来源: https://codeday.me/bug/20191001/1838584.html