Topic: Destruction order of local statics


Author: kieron@us-es.sel.de (Kieron O'Brien US/ESS)
Date: Tue, 24 Aug 93 06:17:35 GMT
Raw View
Must the output of the following C++ program

extern "C" int printf( const char *, ...);

int count = 0;

class A {
 int loc_num;
public:
 A() { loc_num = count++; printf( "%d\n", loc_num); }
 ~A() { printf( "%d\n", loc_num); };
};

void f_1()
{
 static A q;
 static A w[ 2];
}

int main()
{
 static A e;
 static A r[ 2];

 f_1();

 return 0;
}

be

0
1
2
3
4
5
5
4
3
2
1
0

?

Section 6.7 details using a boolean flag to control initialisation
of each local static.

However, Section 3.4 has destruction in the reverse order of
initialisation, for all initialised static objects.

But the order of initialisation of local statics is not known until run
time.

The compilers offer code like

 if (flag == 0) {
  flag = 1;
  call_constructor();
 }

to initialise each local static.  Shouldn't this be:

 if (flag == 0) {
  flag = 1;
  call_constructor();
  register_destructor_with_atexit();
 }

?

Regards

Kieron