0

Consider the following code example:

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 will live longer than c in the above example, but not longer than a.

However, what happens if the return value of Callee() is not assigned to any variable in Caller()? Will the returned object behave like b in the example above? Or will it be destructed before c is created? I guess it's the latter, just want to be sure.

The code example is:

void Caller() {
 SomeClass a(/* initializer here */);
 Callee(); // what is the scope for the object returned by it?
 SomeClass c(/* initializer here */);
}
Serge Rogatch
  • 13,865
  • 7
  • 86
  • 158
  • This question is unclear. It mentions 2 options for function, but never references them later. Also, I do not understand the last sentence. I suggest the question to be rephrased. – SergeyA Sep 12 '17 at 18:47
  • 1
    Objects don't have scopes. They have lifetimes. Names have scopes. – Pete Becker Sep 12 '17 at 18:48

1 Answers1

2

Yes, it will be destructed even before c is created, on account of being a temporary. It's lifetime is the full expression involving the function call.

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

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458