Scope of an inside-parenthesis declared object

2019-07-11 19:43发布

问题:

If I declare an object like this:

void main()
{
    myclass objectA(anotherclass(true,true,0));
}

i.e. I create an objectA and another object "anotherclass" by directly calling the latter's constructor, what is "anotherclass"'s scope?

Does it get destructed only when main() finishes?

回答1:

The temporary gets destructed at the end of the full expression that contains it, i.e. when the call to the constructor of myclass returns.

Per Paragraph 12.2/3 of the C++11 Standard:

Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) 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.

For this reason, if myclass's constructor takes an argument of type anotherClass by reference (either lvalue reference to const or rvalue reference), it shall not store it for future use, because it will be dangling if a temporary is passed, and dereferencing it would be Undefined Behavior.

It is only objectA that goes out of scope and gets destroyed when returning from the main() function.



回答2:

The anotherclass object doesn't have a scope. Scope is a property of names, not of objects, and this object is not named. It's just a temporary object and will be destroyed at the end of the full expression.

Here's the definition of scope (§3.3.1):

In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope.



标签: c++ scope