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

Scope of callee-returned object w.r.t. caller 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() 的 return 值没有分配给 Caller() 中的任何变量,会发生什么? returned 对象的行为会像上面示例中的 b 吗?或者它会在 c 创建之前被销毁吗?我猜是后者,只是想确定一下。

代码示例为:

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

是的,它甚至会在 c 创建之前被销毁,因为它是临时的。它的生命周期是涉及函数调用的完整表达式。

[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.