Search code examples
c++goto

Are goto and destructors compatible?


This code leads to undefined behavior:


void some_func() {
  goto undefined;
  {
    T x = T();
    undefined:
  }
}

The constructor is not called.

But what about this code? Will the destructor of x be called? I think it will be, but I want to be sure. :)


void some_func() {
  {
    T x = T();
    goto out;
  }
  out:
}

Solution

  • Yes, destructors will be called as expected, the same as if you exited the scope early due to an exception.

    Standard 6.6/2 (Jump statements):

    On exit from scope (however accomplished), destructors are called for all constructed objects with automatic storage duration that are declared in that scope, in the reverse order of their declaration.