I wrote the following code.

------ begin file haha.cc ---------------
struct C {
        int i;
};

template <typename T>
struct A {
        A() : p(&C::i) {}
        int C::*p;
};

const A<int> r;

int main()
{
        return 0;
}
------------ end file haha.cc -----------------

And I compiled it with -O2 switch. The exact compilation command given was:
$ g++ -O2 -Wall haha.cc

The compiler didn't produce any errors nor warnings. But when I ran the
generated binary, 'Segmentation fault' came up.

If you (1) make struct A a non-template class or (2) define r as non-const or
(3) declare A::p as a normal pointer or (4) don't give -O2 switch, it compiles
and runs well.

The following is the output from 'gcc -v' command:
$ gcc -v
Reading specs from /usr/lib/gcc/x86_64-redhat-linux/3.4.6/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man
--infodir=/usr/share/info --enable-shared --enable-threads=posix
--disable-checking --with-system-zlib --enable-__cxa_atexit
--disable-libunwind-exceptions --enable-java-awt=gtk --host=x86_64-redhat-linux
Thread model: posix
gcc version 3.4.6 20060404 (Red Hat 3.4.6-10)


-- 
           Summary: initialization failure of global const variable of
                    template class which has a constructor initializing its
                    member which is a pointer to member data when compiled
                    with -O2
           Product: gcc
           Version: 3.4.6
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: kyusic at gmail dot com
 GCC build triplet: x86_64-redhat-linux
  GCC host triplet: x86_64-redhat-linux
GCC target triplet: x86_64-redhat-linux


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

Reply via email to