[LC++]A static const class member and the class constructor.
Shaul Karl
shaulka at bezeqint.net
Tue Dec 18 11:57:08 UTC 2001
Consider the following:
[19:08:53 tmp]$ cat main.cc
#include <iostream>
#include <string>
using namespace std;
class dummy {
public:
dummy() {
cout << test;
}
private:
static const string test;
};
dummy testing;
const string dummy::test("keep testing\n");
int main() {}
[20:27:35 tmp]$ g++-3.0 -Wall -ggdb -o main main.cc
[20:28:43 tmp]$ ./main
Segmentation fault
[20:28:56 tmp]$
Running the above program under gdb shows that the Segmentation fault
is due to the fact that the static const string member is still not
initialized when the constructor is being called. At least this is how
I understand what gdb prints:
(gdb) r
Starting program: /tmp/main
Breakpoint 1, dummy (this=0x400153d8) at main.cc:10
10 cout << test;
(gdb) p test
$1 = {static npos = 4294967295,
_M_dataplus = {<allocator<char>> = {<No data fields>}, _M_p = 0x0},
static _S_empty_rep_storage = {0, 0, 8, 0}}
(gdb)
Is this what the standard dictates or is it a compiler bug?
Since a static class member is not bound to any object of that class
type I do expect it to be initialized before the constructor is being
called to create any objects of that class type.
In short, what am I missing?
[02:41:46 tmp]$ g++-3.0 -v
Reading specs from /usr/lib/gcc-lib/i386-linux/3.0.2/specs
Configured with: ../src/configure -v --enable-languages=c,c++,java,f77,p
roto,objc --prefix=/usr --infodir=/share/info --mandir=/share/man
--enable-shared --with-gnu-as --with-gnu-ld --with-system-zlib
--enable-long-long --enable-nls --without-included-gettext
--disable-checking --enable-threads=posix --enable-java-gc=boehm
--with-cpp-install-dir=bin --enable-objc-gc i386-linux
Thread model: posix
gcc version 3.0.2 (Debian)
[02:42:26 tmp]$
--
Shaul Karl
email: shaulka(at-no-spam)bezeqint.net
Please replace (at-no-spam) with an at - @ - character.
(at-no-spam) is meant for unsolicitate mail senders only.
More information about the tuxCPProgramming
mailing list