相关疑难解决方法(0)

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

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

#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());
}
Run Code Online (Sandbox Code Playgroud)

实例.输出:

Inside f()
Inside g()
Goodbye, cruel world!
Run Code Online (Sandbox Code Playgroud)

因此看起来临时g()被称为......被赋予了什么?

c++ lifetime language-lawyer temporary-objects

11
推荐指数
1
解决办法
791
查看次数