views:

146

answers:

3

Consider the following code:

void foo()
{
    {
        CSomeClass bar;

        // Some code here...

        goto label;

        // and here...
    }

label:
    // and here...
}

Will the destructor of bar be called ?

+9  A: 

1) Yes. 2) Don't do this.

Elaboration: conceptually, this is no different from leaving a loop via a break. goto, however, is strongly, strongly discouraged. It is almost never necessary to use goto, and any use should be scrutinized to find out what's going on.

jwismar
Perfect answer.
mizipzor
2) you do this when you escape loops actually.
Alexandre C.
Actually, goto makes sense in quite a few circumstances.
anon
A break is nicer. At least I know I won't be jumping upwards.
DanDan
+1 and for the original question, a function would probably be the best bet.
The worst about `goto`, `break` and `continue` is that a "return" at the end of a block won't mean "control can't reach beyond this". For that reason, i always try to avoid all three. I personally don't see much difference between `break` and `goto`. Sure there is a bit more worseness in `goto`, but it doesn't add much. All of these have their uses, but all of these complicate the code
Johannes Schaub - litb
+5  A: 

Yes, they will be called.

Update: (it's okay to do this, gotos is not worse than throwing dummy exceptions or using bools/ifs to get out of things. A simple goto inside a function don't make it spaghetti code.)

Viktor Sehr
+1 to negate the egotistical student who felt the need to downvote because they personally think gotos are evil. Gotos have valid uses, people, regardless of what your professors told you.
KevenK
"it's okay to do this, gotos is not worse than throwing dummy exceptions or using bools/ifs to get out of things" Throwing a dummy exception is a terrible way to do this (throwing exceptions is generally extremely expensive) and if it's between that and gotos, I'd definitely prefer gotos. However, writing functions for these cases is certainly the best way to go.
@KevinK - Gotos may have valid uses in theory, but they're extremely rare in practice. I would argue that if it looks like you have to use a goto, the situation at least merits close examination. And for beginning devs, I would suggest avoiding them is a good discipline to learn.
jwismar
@jwismar If a goto helps with code readability, i say go ahead and use it. An example of a legitimate use would be to escape from nested loops.
aCuria
+5  A: 

The C++ Standard says:

On exit from a scope (however accomplished), destructors (12.4) are called for all constructed objects with automatic storage duration (3.7.2) (named objects or temporaries) that are declared in that scope, in the reverse order of their declaration.

So the answer is "yes".

anon
Thanks. That's what I needed.
Alexandre C.