I have a global variable inside an anonymous namespace.
namespace {
std::unordered_map<std::string, std::string> m;
}
A::A() { m.insert(make_pair("1", "2")); } // crasches
void A::insert() { m.insert(make_pair("1", "2")); } // ok
If try to use the map inside the constructor I get Access violation reading location.
But if I use it after A has been initialized it works.
Is this behavior correct?
What is the scope of the
Aobject whose constructor invocation is causing the crash?There are no guarantees as to the order that static initializers are executed, so that if your
Aobject is also a global or static (asmis), it’s quite possible thatmdoes not exist yet in terms of being a validly constructed object, which would mean that your call tostd::unordered_map::insert()would be invoked on uninitialized memory, thus leading to your crash.A solution is to make sure that all of your
Ainstances that depend onmare constructed explicitly by you and not statically/globally (or as the commenter added, if they are in the same TU, to order them properly), or to change the structure ofAsuch that you can call a function on an instance later in order to do the insert. Whether or not this is a valid solution depends more on the overarching usage ofA.