tags:

views:

312

answers:

1

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:
}
+17  A: 

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.

James Hopkin
Got a quote from the standard on that?
Leon Timmermans