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:
}
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With