------- Comment #2 from scovich at gmail dot com  2009-05-09 08:16 -------
Computed gotos can easily make it impossible for the compiler to call
constructors and destructors consistently. This is a major gotcha of computed
gotos for people who have used normal gotos in C++ and expect destructors to be
handled properly. Consider this program, for instance:

#include <stdio.h>
template<int i>
struct foo {
    foo() { printf("%s<%d>\n", __FUNCTION__, i); }
    ~foo() { printf("%s<%d>\n", __FUNCTION__, i); }
};
enum {RETRY, INSIDE, OUTSIDE, EVIL};
int bar(int idx) {
    static void* const gotos[] = {&&RETRY, &&INSIDE, &&OUTSIDE, &&EVIL};
    bool first = true;
    {
    RETRY:
        foo<1> f1;
        if(first) {
            first = false;
            goto *gotos[idx];
        }
    INSIDE:
        return 1;
    }
    if(0) {
        foo<2> f2;
    EVIL:
        return 2;
    }
 OUTSIDE:
    return 0;
}
int main() {
    for(int i=RETRY; i <= EVIL; i++)
        printf("%d\n", bar(i));
    return 0;
}

Not only does it let you jump out of a block without calling destructors, it
lets you jump into one without calling constructors:

$ g++-4.4.0 -Wall -O3 scratch.cpp && ./a.out
foo<1>
foo<1>
~foo<1>
1
foo<1>
~foo<1>
1
foo<1>
0
foo<1>
~foo<2>
2

Ideally, the compiler could analyze possible destinations of the goto
(best-effort, of course) and emit suitable diagnostics:

scratch.cpp:16: warning: computed goto bypasses destructor of 'foo<1> f1'
scratch.cpp:13: warning:   declared here

scratch.cpp:23: warning: possible jump to label 'EVIL'
scratch.cpp:16: warning:   from here
scratch.cpp:22: warning:   crosses initialization of 'foo<2> f2'

In this particular example the compiler should be able to figure out that no
labels reach a live f1 and call its destructor properly. If it's not feasible
to analyze the possible destinations of the computed goto, regular control flow
analysis should at least be able to identify potentially dangerous labels and
gotos, e.g.:

scratch.cpp:16: warning: computed goto may bypass destructor of 'foo<1> f1'
scratch.cpp:13: warning:   declared here

scratch.cpp:23: warning: jump to label 'EVIL'
scratch.cpp:8:  warning:   using a computed goto
scratch.cpp:22: warning:   may cross initialization of 'foo<2> f2'


-- 

scovich at gmail dot com changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |scovich at gmail dot com


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37722

Reply via email to