Are goto and destructors compatible?

旧时模样 提交于 2019-12-18 12:20:08

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/334780/are-goto-and-destructors-compatible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!