In the C++ code below, am I guaranteed that the ~obj() destructor will be called after the // More code executes? Or is the compiler allowed to destruct the obj object earlier if it detects that it's not used?
{
SomeObject obj;
... // More code
}
I'd like to use this technique to save me having to remember to reset a flag at the end of the block, but I need the flag to remain set for the whole block.
Yes, the C++ standard has very specific requirements about when objects are destroyed (in §12.4/10), and in this case it must not be destroyed until after all the other code in the block has finished executing.
All of the answers here address what happens with named objects, but for completeness, you probably should know the rule for temporary/anonymous objects too. (e.g.
f(SomeObjectConstructor()
orf(someFunctionThatReturnsAnObject())
)which basically means that temporarily generated objects persist until the next statement. Two exceptions are for temporaries generated as part of an object's initialization list (in which case the temporary is destroyed only after the object is fully constructed) and if a reference is made to a temporary (e.g.
const Foo& ref = someFunctionThatReturnsAnobject()
) (which case the lifetime of the object is the lifetime of the reference).