Error initializing static member object

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 is not initialized with a = 4 until some time after main (). Prior to this, a = 0. I am trying to access Bar :: foo from the DLL that is statically linking to the library above. And my application references this DLL, but does not have direct access to Bar :: foo. I am using Visual Studio 2008.

Does anyone know what might happen?

+6
c ++
source share
4 answers

$ 3.6.2 / 2- "Variables with static retention time (3.7.1) or stream retention period (3.7.2) must be with zero initialization (8.5) before another initialization is performed.

This explains why you get this value 0

$ 3.6.2 / 4- "Whether dynamic initialization is determined by a nonlocal variable with a static storage duration is the main thing done before the first statement. If initialization is delayed until some point in time after the first statement of the main one, it must occur before the first use of any function or variable defined in that same translation unit as the variable to initialize. "

What you are trying to do leads to undefined behavior, as you are trying to access a variable with a static storage duration that has not yet been initialized, since the code is not yet used in this part of the translation.

+7
source share

Where and when exactly do you get access to Bar::foo ? If it is statically linked to a DLL, then it must be initialized before the "attach" DllMain() is called.

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

+1
source share

Why don't you define a static method in the bar that returns a reference to Foo, and this static method has a static instance of Foo, for example, when it is first called (no matter where), it will be correctly initialized?

 class Bar { public: static Foo& foo() { static Foo inst; return inst; } }; 
+1
source share

What code notices that Bar::foo is not yet initialized? If this is another bit of static initialization in a DLL, then you probably ran into the problem of C ++ static initialization:

+1
source share

All Articles