[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: cannot initialize static pointer class member in __attribute__ ((co
From: |
Paul Pluzhnikov |
Subject: |
Re: cannot initialize static pointer class member in __attribute__ ((constructor)) |
Date: |
Thu, 02 Oct 2008 21:20:47 -0700 |
User-agent: |
Gnus/5.1006 (Gnus v5.10.6) XEmacs/21.4 (Jumbo Shrimp, linux) |
jeremy barrett <jeremyb@gmail.com> writes:
> int* A::x = new int(5);
Note that 'A::x' is initialized to a non-constant value. That means
'gcc' has to initialize it dynamically. In effect, 'gcc' writes a
new function (called static_initialization_and_destruction()),
which is called via exactly the same mechanism as your initAx().
The order of static_init...() and initAx() is not specified,
gcc-3.3.3 for Linux/x86 calls initAx() after static_init...(),
while gcc-4.3.0 calls them in reverse order.
> int B::x = 5;
Here 'B::x' is initialized to a compile-time constant, so 'gcc'
doesn't have to produce any runtime code, it simply puts the variable
into initialized data (.data) section.
> What's happening is:
> -init* functions are called first
> --before setX() calls:
> ---B::x == 5
> ---A::x == NULL (?)
<-------------------------+
> --after setX() calls: |
> ---B::x == 4 |
> ---A::*x == 4 |
> -***magic*** |
|
with gcc-4.x static_initialization... is called here, |
but with gcc-3.3.3 it would have been called there --------+
> -main() is called
> --B::x == 4
> --A::*x == 5 (dammit!)
...
> If anyone knows the order of operations of static member
> initialization (different for pointers, apparently), the .init section
> and whatever else happens before main() in an ELF binary, I probably
> want to hear from you.
It should be enlightening for you to compile the following separate
snippets into assembly and understand the result:
int x = 5; // compile-time constant
int x;
int *px = &x; // link-time constant
int foo();
int x = foo(); // runtime intialization required
Finally, it is entirely pointless to provide initAx() and initBx().
If you want to initialize A::x and B::x to some values, just do
so directly:
int *A::x = new int(4);
int B::x = 4;
Cheers,
--
In order to understand recursion you must first understand recursion.
Remove /-nsp/ for email.