goto 可以在不调用析构函数的情况下跳转函数吗?
goto
是否真的可以在不调用析构函数和其他东西的情况下跳过代码段?
例如
void f() {
int x = 0;
goto lol;
}
int main() {
f();
lol:
return 0;
}
x
不会被泄露吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
警告:此答案仅适用于 C++;仅; C 中的规则完全不同。
不,绝对不是。
认为
goto
是一些低级构造,允许您覆盖 C++ 的内置作用域机制,这是一个神话。 (如果有的话,longjmp
可能容易出现这种情况。)请考虑以下机制,防止您使用标签(包括
case
标签)做“坏事”。1. 标签作用域
不能跨函数跳转:
2. 对象初始化
您无法跳过对象初始化:
如果您返回对象初始化,则 对象的前一个“实例”被销毁:
即使没有显式初始化,您也无法跳转到对象的范围:
...除了 某些各种对象,语言可以处理这些对象,因为它们不需要“复杂”的构造:
3. 跳转遵守其他对象的范围
同样,具有自动存储期限的对象不当您
进入
范围之外时“泄露”:结论
上述机制确保
goto
不会让您破坏语言。当然,这并不自动意味着您“应该”使用
goto
来解决任何给定的问题,但它确实意味着它并不像常见的神话引导人们相信。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.