Re: Dynamic initialization of namespace scope objects may be deferred until first use?
On Sep 24, 6:08 pm, JoshuaMaur...@gmail.com wrote:
In the C++03 standard, 3.6.2/4, it says that globals may have their
initialization deferred until the first use of a function or object
from that translation unit.
I'm sure this issue has been discussed before, either here or in
comp.std.c++. Search for posts by James Kanze. My responses below are
based on what I remember from those discussions; please do not take
them as authoritative.
My questions are:
1- Why is that in the standard? The intent was to allow
implementations to lazy initialize translation units? Seems to be
almost an aborted attempt at shared libraries.
Indeed. Apparently it was added to (semi-)legalise dynamically loaded
shared libraries, which for obvious reasons may not be able to
initialise globals before the beginning of main.
2- Do any actual compilers do this? If any actual compiler
implementation does this, hopefully they do it in a thread-safe way?
Other than in shared libraries I understand that no compilers actually
do this. If I recall correctly, it was claimed to be impossible to do
correctly (at least in some cases).
3- This all rests upon the implicit assumption that no one creates
threads before main is called. Is this a fair assumption from real
world code? It just seems that what limited guarantees we have
concerning the order of construction of globals goes out the window if
there's multiple threads before main starts.
I think it's a sensible requirement to make if you're writing an
application; I always do so. (It's a good idea to document it of
course.) A third-party thread (i.e. one not created directly by the
application) is unlikely to be able to affect the application's
globals unless the application has explicitly given it control, which
should be avoidable.
When writing a library (for widespread use) the question is less clear-
cut. I think it's reasonable to make such a requirement of the library
user, but it must be documented clearly. Of course, without
documentation who knows what threading guarantees a library gives?
4- I assume that when a shared library is loaded, all of the globals
are constructed before the load call returns, or it's delayed in a
thread-safe way. (Quite analogous to question 3.) Correct?
Obviously implementation-specific. I can only speak for Windows, which
initialises the globals whilst loading the library, from the DllMain
entry function. This means that when creating a dll it is essential to
avoid doing anything in a global constructor which can't be done in a
DllMain, which is a whole bunch of stuff which is not very well
documented. See
http://msdn.microsoft.com/en-us/library/ms682583.aspx
(or search DllMain) for slightly more information. And I speak from
bitter experience :-).
Yechezkel Mett
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]