Take the 2-minute tour ×

Following is a simple case of counting objects:

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

Now, its object and static member are declared 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 ?

share|improve this question
POD are zero-initialized. The forward declaration of the static really ought to be forward but it may depend on where A is declared is the scope be it global, a namespace, etc makes a significant difference as to how things are initialized. –  AJG85 Jun 29 '11 at 6:35
add comment

1 Answer

It depends.


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.

share|improve this answer
The results may be unexpected, but they will still be well defined even without the constant initialization. –  Dennis Zickefoose Jun 29 '11 at 7:03
add comment

Your Answer


