This is the mail archive of the
mailing list for the GCC project.
RE: Attribute destructor function and C++ destructors
- From: "John \(Eljay\) Love-Jensen" <eljay at adobe dot com>
- To: "Simon White" <s_a_white at email dot com>, <gcc-help at gcc dot gnu dot org>
- Date: Fri, 17 Nov 2006 05:24:43 -0800
- Subject: RE: Attribute destructor function and C++ destructors
- References: <20061117105152.012631024D@ws1-3.us4.outblaze.com>
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:
static Foo 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: