title: Storing pointers in unordered_map in C++
body: <p>So my code is using a <code>tr1::unordered_map&lt;int, ContainerA&gt;</code> where ContainerA is something like this :</p>
  
  <pre><code>class ContainerA
  {
      int* _M_type; 
      unsigned int _M_check;
      int _M_test;
      unsigned int _M_any;
      index _M_index;
      index _M_newindex;
      objectB _M_cells[10];
      vector&lt;int&gt; _M_mapping[10];
  }
  </code></pre>
  
  <p>The number of entries in my unordered_map is of the order of millions and at every timestep, tens of thousands (if not hundreds of thousands) of entries get deleted and added. It seems like much of my computing time is used up allocating individually each instance of the ContainerA class.</p>
  
  <p>A solution I propose for speeding things up is to dynamically allocate an estimated number of ContainerA objects needed at the start, and replacing the unordered_map to ContainerA objects by an unordered_map to pointers <code>tr1::unordered_map&lt;int, ContainerA*&gt;</code>.</p>
  
  <p>This seems like a good idea to me, however after doing some research, it does not seem to me like this approach is common which is why I am wondering if I am missing something.</p>
  
  <p>Are there any drawbacks to this approach apart from the additional memory overhead of the pointers?</p>
  
  <p>Edit :
  As pointed out in the comments below, the problem might lie in my memory allocation. I allocate my memory as follows :
  I construct a <code>ContainerA</code> object using its constructor <code>ContainerA  obja(int* type, int test)</code>. In this phase, the <code>ContainerA</code> constructor lets the <code>objectB</code> array and the <code>vector&lt;int&gt;</code> array get default constructed.</p>
  
  <p>After constructing my <code>ContainerA</code>, all my <code>vector&lt;int&gt;</code> and <code>objectB</code> need to allocate some memory on the heap. This is probably the time-consuming phase.</p>
  
  <p>It would probably be possible to avoid deallocating and reallocating memory without using an <code>unordered_map</code> to pointers, but by simply swapping memory contents as suggested. However, I would need to have some sort of way of keeping track of which objects are not used anymore and that sounds somehow more tedious than switching to a pointer array?</p>