Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static member object initialization failure

Tags:

c++

I have a static library with the following code:

h file:

class Foo
{
public:
   Foo()
   {
       a = 4;
   }

   int a;
};


class Bar
{
public:
    static const Foo foo;
};

cpp file:

const Bar::foo = Foo();

My problem is that Bar::foo does not get initialized with a=4 until some time after main(). Before then a=0. I'm trying to access Bar::foo from a DLL which statically links to the library above. And my application links to that DLL but does not access Bar::foo directly. I'm using Visual Studio 2008.

Does anyone know what could be going on?

like image 665
Matthew Avatar asked Oct 15 '10 05:10

Matthew


2 Answers

$3.6.2/2- "Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place."

That explains why you get that value of 0

$3.6.2/4- "It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or variable defined in the same translation unit as the variable to be initialized."

So what you are trying to do leads to undefined behavior as you are attempting to access a variable with static storage duration which has not yet been initialized as no code in that translation unit has been used as yet.

like image 106
Chubsdad Avatar answered Sep 21 '22 23:09

Chubsdad


Where and when exactly are you accessing Bar::foo? If it's statically linked into the DLL, then it should be initialized before DllMain()'s 'process attach' is called.

Are you setting a different entry point for the DLL than the default of _DllMainCRTStartup?

like image 39
Michael Burr Avatar answered Sep 18 '22 23:09

Michael Burr