Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are goto and destructors compatible?

Tags:

c++

goto

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:
}
like image 492
Sergey Skoblikov Avatar asked Dec 02 '08 17:12

Sergey Skoblikov


People also ask

Why is goto not reliable?

It is easy to get caught in an infinite loop if the goto point is above the goto call. This is almost guaranteed if there is no reliable escape from the code, such as a RETURN statement within a conditional statement.

When should goto be used?

The goto statement can be used to alter the flow of control in a program. Although the goto statement can be used to create loops with finite repetition times, use of other loop structures such as for, while, and do while is recommended. The use of the goto statement requires a label to be defined in the program.

Is Goto efficient C++?

Yes, the machine code generated from goto will be a straight JUMP. And this will probably be faster than a function call, because nothing has to be done to the stack (although a call without any variables to pass will be optimized in such a way that it might be just as fast).


1 Answers

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.

like image 119
James Hopkin Avatar answered Oct 03 '22 12:10

James Hopkin