19

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:
}
Sled
  • 18,541
  • 27
  • 119
  • 168
Sergey Skoblikov
  • 5,811
  • 6
  • 40
  • 49
  • The first code sample does not lead to undefined behavior, it's illegal and won't compile. – Adam Rosenfield Dec 02 '08 at 18:49
  • "won't compile" is an example of undefined behavior, i think. The book I'm reading now says "undefined behavior". – Sergey Skoblikov Dec 02 '08 at 18:59
  • 2
    The two are technically different: if the compiler is required to reject the program, that's "less bad" from the programmer's POV than something that might compile and set his house on fire when it runs. Some compilers reject things which are legal but which that compiler knows will be undefined. – Steve Jessop Dec 02 '08 at 19:21
  • 5
    @SergeySkoblikov: The book is wrong! UB and ill-formed are _very_ different. – Lightness Races in Orbit Dec 15 '11 at 15:10

1 Answers1

45

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
  • 13,797
  • 1
  • 42
  • 71