Are goto and destructors compatible?

2019-02-04 08:53发布

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:
}

标签: c++ goto
1条回答
手持菜刀,她持情操
2楼-- · 2019-02-04 08:58

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.

查看更多
登录 后发表回答