Scope of an inside-parenthesis declared object

北城余情 提交于 2019-12-12 18:28:21

问题


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.



来源:https://stackoverflow.com/questions/15580903/scope-of-an-inside-parenthesis-declared-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!