被调用者返回的对象的范围w.r.t.调用者局部变量?

时间:2017-09-12 18:42:49

标签: c++ scope return-value c++17 local-variables

请考虑以下代码示例:

SomeClass Callee() {
  // Option 1:
  return SomeClass(/* initializer here */);

  // Option 2:
  SomeClass tmp(/* initializer here */);
  // Do something to tmp here
  return tmp;
}

void Caller() {
 SomeClass a(/* initializer here */);
 SomeClass b = Callee();
 SomeClass c(/* initializer here */);
}

AFAIK,b的有效期超过上述示例中的c,但不会超过a

但是,如果Callee()的返回值未分配给Caller()中的任何变量会怎样?在上面的示例中,返回的对象是否会像b一样?或者在创建c之前它会被破坏吗?我想这是后者,只是想确定。

代码示例是:

void Caller() {
 SomeClass a(/* initializer here */);
 Callee(); // what is the scope for the object returned by it?
 SomeClass c(/* initializer here */);
}

1 个答案:

答案 0 :(得分:2)

是的,即使在创建c之前它也会被破坏,因为它是临时的。它的生命周期是涉及函数调用的完整表达式。

[class.temporary]/4

  

当实现引入类的临时对象时   有一个非平凡的构造函数([class.ctor],[class.copy]),它应该   确保为临时对象调用构造函数。   类似地,析构函数应该被调用为临时的   非平凡的析构函数([class.dtor])。 临时对象是   作为评估全表达的最后一步被破坏了   (词法上)包含创建它们的点。这是真的   即使该评估以抛出异常结束。价值   破坏临时对象的计算和副作用是   仅与完整表达相关联,而不与任何特定表达相关联   子表达式。

相关问题