问题
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
?
回答1:
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.
回答2:
The standard determines that the correct behavior for that code is printing "123". Compilers are allowed to change the code as much as they want while maintaining the same semantics (as-if rule), and reordering of the code here would change the semantics, so a compliant compiler is not allowed to do it.
回答3:
The constructors may have side effects. For example they might implement a mutex i.e. The constructor locks and the desctuctor unlocks a mutex. Therefore the 123 is required.
来源:https://stackoverflow.com/questions/7223734/automatic-object-destruction