On Tuesday, December 11, 2018 at 9:10:38 AM UTC-5, Michael Powell wrote:
In that message, he states that he expects the dtor to be run
immediately before the '}' that terminates the scope in which the object
was defined, which is correct. He then indicates that he was surprised
to see the dtor actually executed immediately after a particular
semicolon. He doesn't indicated how he determined that the dtor was
executed, but that's a relatively minor point. The major point is that
the semi-colon he's referring to is immediately followed by the '}' that
he's referring to, so there's no conflict between the expected and
observed timing of the dtor call.
> Basically, I am observing that dtors are being invoked much earlier
> than the end of scope when I would expect, even in debug mode. If it
> were a "release mode" I might understand that this sort of
> optimization, I gather, would take place, but not in debug mode.
That depends a lot upon how you define "release mode" and "debug mode", and also upon whether or not the implementation you're using agrees with those definitions. The compiler that I've used most frequently over the past or two performs some annoyingly aggressive optimizations even when invoked with the lowest possible optimization level.
> What's the point of having a dtor if the scope is not respected by the
> compiler?
123456789012345678901234567890123456789012345678901234567890123456789012
There's something that's not at all relevant to the code in that
stackoverflow question, but which might be relevant to your code (I
can't tell, because I haven't seen your code). The only thing that
matters, as far as conformance with the C++ standard is concerned, is
whether or not a program produces the same "observable behavior" after optimization as would be permitted before optimization. "observable
behavior" is a piece of jargon defined by the C++ standard in section
4.1.1 - it does NOT mean "behavior which can be observed". It refers to
any type of behavior that falls into one of a listed set of categories.
Any behavior that doesn't fall into one of those categories is not
"observable behavior", no matter how easy it is to observe that
behavior (for instance, by using a debugger).
Therefore, if an implementation can produce permitted observable
behavior despite executing the dtor early, than it is permitted to do
so, and that might be precisely what you're seeing.
A key point to be aware of: if it matters to you whether or not the dtor
is executed early, there's a pretty good chance that the reason why i
matters to you involves "observable behavior". If so, such
optimizations are NOT permitted. For instance, if you add code before
the end of the scope, inside the dtor itself, and after the end of the
scope which displays information that would allow you to tell what order
those pieces of code occurred in, then it would have to display that
information in that order.