title: Create object after ID is allocated in std::unordered_map
body: <p>I have an std::unordered_map which stores an integer with an object. Here's some code for you to understand:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;unordered_map&gt;
  #include &lt;cstdlib&gt;
  using namespace std;
  
  class Foo
  {
  public:
      Foo()
      {
          cout &lt;&lt; "Foo created!" &lt;&lt; endl;
      }
  
      ~Foo()
      {
  
      }
  };
  
  typedef std::unordered_map&lt;int, Foo*&gt; FooMap;
  FooMap fm;
  
  int allocateID()
  {
      cout &lt;&lt; "Allocating ID" &lt;&lt; endl;
      return rand() % 100;
  }
  
  void add()
  {
      fm.emplace(allocateID(), new Foo());
  }
  
  int main()
  {
      srand(time(NULL));
  
      add();
  
      return 0;
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Foo created!
  Allocating ID
  </code></pre>
  
  <p>The problem here is that the object <code>Foo</code> is created <strong>before</strong> an ID is allocated! I tried adding  a mutex lock on <code>allocateID</code>; it didn't work because <code>allocateID()</code> runs <strong>AFTER</strong> the object is created.</p>
  
  <p>How can I modify this program such that <code>Foo</code> is created <strong>AFTER</strong> the ID is allocated?</p>
  
  <p>EDIT:</p>
  
  <p>I've played around with the code and used a solution herein to demonstrate:</p>
  
  <pre><code>void add(int id, Foo *f)
  {
      auto iden = id;
      auto foo = f;
      fm[iden] = foo;
  }
  
  void add(Foo *f, int id)
  {
      auto iden = id;
      auto foo = f;
      fm[iden] = foo;
  }
  
  void add()
  {
      int id = allocateID();
      fm[id] = new Foo();
  }
  </code></pre>
  
  <p>In the first <code>add()</code> function, the output remains the same. This doesn't solve the problem.</p>
  
  <p>In the second <code>add()</code> function, the output is different, instead producing:</p>
  
  <pre><code>Allocating ID
  Foo created!
  </code></pre>
  
  <p>And in the third function, it has been modified with one of the solutions: this function also produces the desired output. The problem with the third function is that it's highly unlikely there would be an empty <code>add()</code> function realistically. The only culpable way of solving this issue is to pass the object first <strong>AND THEN</strong> the id. This is probably because the arguments are read from right to left, regardless of the entry requirements because they are created after the arguments are read anyway.</p>