Attribute destructor function and C++ destructors

John (Eljay) Love-Jensen
Fri Nov 17 13:25:00 GMT 2006

Hi Simon,

You are bumping into the order-of-construction (OoC) & order-of-destruction (OoD) issue in C++.

My first recommendation is, if possible, never ever ever ever ever ever ever rely on "stuff that happens before main()", and "stuff that happens after main()".  Put explicit initialization in main using RAII.  Life will be better.

But if you just have to have initialization/cleanup relying on auto-magic construction/destruction of statics...

Are the globals in the same translation unit (i.e., static globals)?  If they are, they are slightly better behaved than if the statics are being used across translation units.

If the static globals are in the same translation unit, where you place them in the translation unit determines their OoC and LIFO OoD.  If they do not have external linkage (extern globals), then you can rely on their OoC.

If they have external linkage (extern globals), then it is possible to access them before they are constructed.  There's no Standard C++ means of specifying inter-translation unit OoC for static globals.  If the statics are being used across translation units, bury your statics inside a getter:

Foo& GetFoo()
  static Foo foo;
  return foo;

If you are still running into problems, consider using the Nifty Counter pattern (aka Schwarz counter), which is what the I/O Streams use:


More information about the Gcc-help mailing list