title: Moving C++ objects, especially stl containers, to a specific memory location
body: <p>I am working with a memory manager that, on occasion, wants to defragment memory. Basically, I will go through a list of objects allocated by the memory manager and relocate them:</p>
  
  <pre><code>class A {
    SomeClass* data; // This member is allocated by the special manager
  };
  
  for(... each instance of A ...) 
      a.data = memory_manager.relocate(a.data);
  </code></pre>
  
  <p><code>memory_manager.relocate()</code> will <code>memcpy()</code> the contents of data to a new location, and return the pointer.</p>
  
  <p>Although it's generally not idiomatic to <code>memcpy()</code> C++ classes, it seems to be a useful solution in this case, considering that I control the implementation of the (few) classes that will be used with the memory manager. </p>
  
  <p>The problem is that one of those classes uses <code>std::map</code>, which is an opaque class as far as I am concerned. I certainly don't imagine I can <code>memcpy()</code> it. I may not be able to use std::map in any case. For all I know it could allocate several pieces of memory.</p>
  
  <p>The best workaround I can think of is simple enough. Due to the fact that the fragmented memory manager will put new allocations at more beneficial locations, all I need to do is allocate it anew and then delete the old:</p>
  
  <pre><code>for(... each instance of A ...) {
      stl::map&lt;something&gt;* tmp = a.the_map;
      a.the_map = new stl::map&lt;something&gt;(tmp);
      delete tmp;
  }
  </code></pre>
  
  <p><br><br>
  In any case, this lead me to wonder: </p>
  
  <p>Does C++ have semantics or idioms to move/copy an object into a specific memory location?</p>
  
  <p>Is it possible to move the contents of an stl container to a specific memory location?</p>
  
  <p><br>
  Edit: Although I didn't point it out, I would obviously pass an allocator parameter to std::map. Based on the informative answers I got, I realize the workaround I posted in my initial question would probably be the only way to reduce fragmentation. By using the map's copy constructor (and the allocator template parameter), all memory used by the map would be properly re-allocated.</p>
  
  <p>As a comment pointed out, this is mostly a theoretical problem. Memory fragmentation is rarely something to worry about.</p>