Re: When is the non-local static variable constructor run?
On 2012-01-18 21:10, DeMarcus wrote:
What I want is a side-effect of the sc constructor; I want to do a
self-registration of that sc instance in a global vector. And I would
like to have that global vector filled with pointers to all variables
similar to sc before main starts or at some other point that I can
Also, I do not want to be forced to refer sc or anything in
that file to have the constructor run.
But exactly this is nothing you can rely upon.
Am I correct claiming that this article may not work then?
(Looking at Listing Three and Listing Five)
(The links don't work, scroll down instead)
Let me start with the following remark: The precise ordering of
non-local variable initialization is not exactly specified to allow for
different implementation strategies of C++ programs, typically based on
some form of static or dynamic libraries. Since "libraries" have no
specification as part of the C++ standard, you will not get sufficient
guarantees from the wording to deduce the behaviour, therefore my above
statement for caution. But unless you perform some special form of
dynamic library loading, the observable effects of "global statics"
should all happen before main - I have not seen an implementation which
does otherwise. *If* there should be implementations that do not provide
this guarantee, I would really like to know of them (and the conditions
when this happens).
You should also be aware that so-called "static libraries" typically
behave a bit different in this regard, because they normally don't
construct global objects that are not odr-used by the library-user. To
get around this problem for those libraries, a simple workaround is to
define a global object of internal linkage (either via the static
keyword or via an unnamed namespace) in every public header of this
library which behaves similar to as if FileConverterProxy<T> mentioned
in the article would be a singleton for each T. This is more or less an
elegant alternative to the nifty-counter idiom that is used to specify
the construction and destruction semantics of the global C++ IO stream
One obvious defect in the article is the usage of the global variable
gConverterStore, because this is (generally) constructed without order
in regard to the different FileConverterProxy<T> objects in other TUs.
This is easy to fix by the usage of the "Meyers Singleton" idiom (or
others with similar construction-order guarantees), see i.g.
HTH & Greetings from Bremen,
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]