开发者

Is it well defined to declare an object of the class before its static variable in global space?

Following is a simple case of counting objects:

struct A
{
  static int count;
  A () { ++ count; }
};

Now, its object and static member are 开发者_如何学Pythondeclared as:

A obj;  // comes 1st
int A::count = 5;  // comes 2nd

g++ produces expected result. But since, definition of A::count comes after one of the A instance in global space, shouldn't it be undefined behavior ?


It depends.

3.6.2

The storage for objects with static storage duration (basic.stc.static) shall be zero-initialized (dcl.init) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (basic.types) with static storage duration initialized with constant expressions (expr.const) shall be initialized before any dynamic initialization takes place.

Since you have a POD initialized with a constant expression, it will be statically initialized, i.e. before any constructors run. Change any of these conditions, and unexpected results are likely to occur.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜