Goto out of a block: do destructors get called?

后端 未结 4 751
陌清茗
陌清茗 2020-12-28 12:14

Consider the following code:

void foo()
{
    {
        CSomeClass bar;

        // Some code here...

        goto label;

        // and here...
    }

lab         


        
4条回答
  •  长情又很酷
    2020-12-28 12:39

    Yes, as everyone else says. C++ specifies/mandates this.

    But just to add to that, for completeness: if your goto uses the computed-goto extension found in some compilers -- gcc, clang, possibly others but not including MSVC last I knew -- whether or not the object's destructor will be called is pretty hazy. When a goto goes to a single location, it's very clear what destructors must be called before the control-flow transfer. But with a computed goto, different destructors might need to dynamically be called, to give the "expected" semantics. I'm not sure what compilers that implement this extension do, in those cases. My memory from encountering this is that clang warns when a computed-goto might leave a scope with an object with a non-trival destructor, claiming the destructor won't be called. In some cases that might be fine, in others not. I don't know offhand what other compilers do. Just be aware of the issue if you want to use computed gotos in concert with objects with non-trivial destructors.

提交回复
热议问题