First of all, the __attribute__((constructor))
function is an implementation-defined compiler extension, so the C++ standard is no help in understanding its behaviour.
Clang's attribute reference doesn't actually mention it, so we have to go back to GCC's documentation, as clang implements this attribute in order to be compatible with the GNU dialects of C/C++/Objective-C.
The constructor
attribute causes the function to be called automatically before execution enters main ().
No specified relative order vs C++ static initialisers so far. However, it soon becomes clear that the constructor function runs before static C++ initialisers:
You may provide an optional integer priority […] A constructor with a smaller priority number runs before a constructor with a larger priority number; […] The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects (see C++ Attributes).
If you then look at the documentation for the init_priority()
attribute you find its priority
argument to be:
[…] a constant integral expression currently bounded between 101 and 65535 inclusive. Lower numbers indicate a higher priority.
In other words, you can put multiple __attribute__((constructor))
functions in a specific relative order with priority 0…100, and statically initialised C++ objects in an order 101…65535 to override the default behaviour of objects being initialised in the order of definition in a compilation unit, and order being unspecified across compilation units. But this also means that the last constructor function always runs before the first C++ static initialiser.
This explains the behaviour you are seeing. Your constructor function runs before aMap1
's constructor. aMap1
is automatically constructed, but not until after the constructor function has completed.
For ways to solve this problem, see the relevant entry in the C++ FAQ.