开发者

Static member object initialization failure

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 ge开发者_如何学Pythont 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?


$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.


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?


Why don't you define a static method in bar which returns a reference to Foo, and in that static method, have a static instance of Foo, such that when it's first called (irrespective of where), it will get correctly initialised?

class Bar
{
  public:
    static Foo& foo()
    {
      static Foo inst;
      return inst;
    }
};


What code is noticing that Bar::foo isn't initialized yet? If it's another bit of static initialization in the DLL then you're probably running into C++'s static initialization order problem:

  • from the C++ FAQ: What's the "static initialization order fiasco"?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜