help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

cannot initialize static pointer class member in __attribute__ ((constr


From: jeremy barrett
Subject: cannot initialize static pointer class member in __attribute__ ((constructor))
Date: Thu, 2 Oct 2008 13:46:35 -0700 (PDT)
User-agent: G2/1.0

Hi everyone. I've been banging my head against the wall and my queries
against the google on this one for a couple of days and cannot find
another documented case, so here it is:

This chunk:

//file A.h
class A{
public:
 static void setX(int v) { delete x; x = new int(v); }
 static int getX() { return x?*x:0xdeadbeef; }
private
 static int* x;
};
//file A.cpp
#include "A.h"
int* A::x = new int(5);
//file ctor_A.cpp
#include "A.h"
static void __attribute__ ((constructor)) initAx();
void initAx(){ A::setX(4); }

and this chunk:

//file B.h
class B{
public:
 static void setX(int v) { x = v; }
 static int getX() { return x; }
private
 static int x;
};
//file B.cpp
#include "B.h"
int B::x = 5;
//file ctor_B.cpp
#include "B.h"
static void __attribute__ ((constructor)) initBx();
void initBx(){ B::setX(4); }

do not yield the same behavior.

E.g. if A, B and the associated ctors are built into a shared library,
programs using the library will find different values for A::getX()
and B::getX() upon entering main(), like so:

//file main.cpp
#include "A.h"
#include "B.h"
#include <stdio.h>

int main(int argc, char** argv){
 printf("%d\n",A::getX());     //5
 printf("%d\n",B::getX());     //4
 exit(0);
}

>From everything I've read, B is exhibiting the appropriate behavior
(not to mention the behavior I want).

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***
-main() is called
--B::x == 4
--A::*x == 5 (dammit!)

I have more information (and a tarball of example code), but i think
this gets the point across.

Has anyone seen this before, or is it so obvious that people don't
feel the need to write about it on the internet (I'm not being
facetious -- I could really be missing something here)?

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.

thanks!
jeremy


reply via email to

[Prev in Thread] Current Thread [Next in Thread]