Is it true that goto
jumps across bits of code without calling destructors and things?
e.g.
void f() {
int x = 0;
goto lol;
}
int main() {
f();
lol:
return 0;
}
Won't x
be leaked?
Is it true that goto
jumps across bits of code without calling destructors and things?
e.g.
void f() {
int x = 0;
goto lol;
}
int main() {
f();
lol:
return 0;
}
Won't x
be leaked?
Warning: This answer pertains to C++ only; the rules are quite different in C.
No, absolutely not.
It is a myth that
goto
is some low-level construct that allows you to override C++'s built-in scoping mechanisms. (If anything, it'slongjmp
that may be prone to this.)Consider the following mechanics that prevent you from doing "bad things" with labels (which includes
case
labels).1. Label scope
You can't jump across functions:
2. Object initialisation
You can't jump across object initialisation:
If you jump back across object initialisation, then the object's previous "instance" is destroyed:
You can't jump into the scope of an object, even if it's not explicitly initialised:
... except for certain kinds of object, which the language can handle regardless because they do not require "complex" construction:
3. Jumping abides by scope of other objects
Likewise, objects with automatic storage duration are not "leaked" when you
goto
out of their scope:Conclusion
The above mechanisms ensure that
goto
doesn't let you break the language.Of course, this doesn't automatically mean that you "should" use
goto
for any given problem, but it does mean that it is not nearly as "evil" as the common myth leads people to believe.