c++ - goto 和析构函数兼容吗?

标签 c++ goto

此代码导致未定义的行为:


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/

相关文章:

c++ - 玩具 shell 管道不正确

c++ - std::async 的奇怪行为

c++ - 为什么 “strcat” 被认为是 “unsafe” ?

c++ - 我在自学C++,并在代码中陷入了计时器。尝试在上一条消息之后3秒发出一条消息

c++ - 什么是间接 goto 语句?

c# - GOTO 与 DO WHILE 的区别

c - while(1) .. break 而不是 goto

C++,在静态成员函数中使用 'this' 的宏的解决方法

c++ - 不混淆的字符串函数

c - C switch 语句中的最终子句(可能使用 goto)