Is the destruction of automatic objects (objects created on the stack) guaranteed to be executed not before they go out of scope?
To clarify:
#include <iostream>
class A {
public:
A() {
std::cout << "1";
}
~A() {
std::cout << "3";
}
};
void test123() {
A a;
std::cout << "2";
}
To print "2"
, a
is not required any more, so theoretically the compiler could try to optimise and destroy a
as soon as it is not needed any more.
Can I rely on the above function always printing 123
?
The destruction order of stack objects is strictly defined - they execute in reverse order of declaration, when you leave the scope (either by running off the end of the {}
, or by return
, or by an exception). So, you will always see 123
there.
Note, however, that compiler optimizations are governed by the 'as-if' rule. In other words, a compiler can destroy an object early, as long as the resulting program behaves 'as-if' it had been destroyed at the normal time. In this case, because you do output, the compiler must schedule the output at the proper time. However, if you had, for example, delete
d a pointer to a primitive type, and the compiler can prove there are no other outstanding pointers to that value, it could, in principle, move that delete
earlier. The key is that no conforming program is capable of noticing this optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With