Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic object destruction

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?

like image 696
bitmask Avatar asked Dec 10 '22 06:12

bitmask


1 Answers

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, deleted 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.

like image 169
bdonlan Avatar answered Feb 19 '23 07:02

bdonlan