此代码导致未定义的行为:
void some_func() {
goto undefined;
{
T x = T();
undefined:
}
}
构造函数没有被调用。
但是这段代码呢? x 的析构函数会被调用吗?我想会的,但我想确定一下。 :)
void some_func() {
{
T x = T();
goto out;
}
out:
}
最佳答案
是的,析构函数将按预期调用,就像您因异常提前退出作用域一样。
标准 6.6/2(跳转语句):
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.
关于c++ - goto 和析构函数兼容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/334780/