title: '_Wherenode was nullptr' when adding to static std::map
body: <p>I've been following <a href="https://www.bfilipek.com/2018/02/factory-selfregister.html" rel="nofollow noreferrer">this tutorial / example</a> on creating a self-registering type in C++17. But I've run into a problem: Upon a type's attempt to register, my program terminates with the error <code>read access violation. _Wherenode was nullptr.</code> This error occurs in the standard library's <code>std::_Tree&lt;std::Tmap_traits&lt;...&gt;::_Lbound</code> method.</p>
  
  <p>This is my source code, nearly identical to that on the page (with some tweaks to fix errors the original code had:)</p>
  
  <pre><code>class Entity { ... }; // Contents irrelevant
  
  class EntityTypeFactory {
  public:
      using TCreateMethod = std::function&lt;Entity* ()&gt;;
  
      EntityTypeFactory() = delete;
  
      static Entity* Create(const std::string&amp; type);
  
      static bool Register(const std::string&amp; name, TCreateMethod func);
  
  private:
      static std::map&lt;std::string, TCreateMethod&gt; s_methods;
  };
  
  #define REG_ENT(TYPE) class TYPE##Creator { private: static bool s_created; }; \
  bool TYPE##Creator::s_created = EntityTypeFactory::Register(#TYPE, []() -&gt; Entity* { return new TYPE(); });
  
  
  std::map&lt;std::string, EntityTypeFactory::TCreateMethod&gt;* EntityTypeFactory::s_methods;
  
  Entity* EntityTypeFactory::Create(const std::string&amp; type)
  {
      if (s_methods == nullptr) return nullptr;
  
      return (*s_methods)[type]();
  }
  
  bool EntityTypeFactory::Register(const std::string&amp; name, TCreateMethod func)
  {
      if (s_methods == nullptr)
          s_methods = new std::map&lt;std::string, TCreateMethod&gt;();
  
      (*s_methods)[name] = func;
      return true;
  }
  
  class Foo : public Entity {}; // Contents irrelevant
  
  REG_ENT(Foo)
  </code></pre>
  
  <p><strong>Edit:</strong> This seems to have to do with the linking order, as if I place my test implementation <code>Foo</code> in a source file which would occur earlier than <code>Entity</code> when sorted alphabetically (as this seems to be VC++'s way of choosing link order), it fails, but if I place this implementation in a file which is linked <em>after</em>, it works as intended. I still am not sure how to make it work universally though.</p>