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?
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):
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:
For this reason, if
myclass
's constructor takes an argument of typeanotherClass
by reference (either lvalue reference toconst
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 themain()
function.