This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: Attribute destructor function and C++ destructors


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:

http://www-d0.fnal.gov/KAI/doc/tutorials/static_initialization.html

HTH,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]