title: How to implement deep copy or clone of an object that has circular references?
body: <p>I have such hierarchy:</p>
  
  <pre><code>class Sphere;
  class Cube;
  class SpherePair;
  
  class Entity {};
  
  class Cube : public Entity {
  public:
    list&lt;Sphere*&gt; spheres_;
  };
  
  class Sphere : public Entity {
  public:
    Cube       *cube;
    SpherePair *spherepair;
  };
  
  class SpherePair : public Entity {
  public:
    Sphere *first;
    Sphere *second;
  };
  </code></pre>
  
  <p><strong>What I want is to make a clone of Cube object and all the objects connected to it (Sphere, SpherePair, Cube).</strong> </p>
  
  <p>Cube has Spheres inside, each Sphere is a half of SpherePair object. SpherePair points to Spheres which are in separate Cubes or in one same Cube.</p>
  
  <p>This is needed for proper Undo functionality. </p>
  
  <p>I would also like to have a map of old and cloned entities:</p>
  
  <pre><code>std::map&lt;Entity*, Entity*&gt; old_new;
  </code></pre>
  
  <p><strong>Added:</strong> Before these circular references I had a simple clone functionality:</p>
  
  <pre><code>class Entity {
   public:
    virtual Entity* clone() = 0;
  }
  </code></pre>
  
  <p>It was used in such a scheme:</p>
  
  <pre><code>std::vector&lt;Entity*&gt; selected_objects_;
  
  void move(const vec3f &amp;offset) {
    document-&gt;beginUndo();
  
    for(int i = 0; i &lt; selected_objects_.size(); ++i) {
      Entity *cloned = selected_objects_[i]-&gt;clone();
  
      cloned-&gt;move(offset);
  
      selected_objects_[i]-&gt;setDeleted(true);
      document-&gt;pushToUndo(selected_objects_[i]);
      document-&gt;addEntity(cloned);
    }
  
    document-&gt;endUndo();
  }
  </code></pre>