Implementing .dup / clone for class hierarchies

Bill Baxter dnewsgroup at billbaxter.com
Sun Dec 9 18:47:32 PST 2007


I like the .dup idea in D, but how do you implement it for a class 
hierarchy?  Are there existing libraries that deal with this problem well?

In a nutshell the problem is this:

class Base
{
     Base dup() {
        auto ret = new Base();
        // copy members of this to ret
        return ret;
     }
}

class DerivedA : Base
{
     DerivedA dup() {
        auto ret = new DerivedA();
        // copy members of base to ret
        // copy members of this to ret
        return ret;
     }
}

class DerivedB : Base
{
     DerivedB dup() {
        auto ret = new DerivedB();
        // copy members of base to ret
        // copy members of this to ret
        return ret;
     }
}


The main issue is the "copy members of base to ret" part.
The way I've been doing it is to add a virtual copy method to every 
level of the hierarchy:

      /** copy other on top of this */
      void copy(Class other) {
          this.x = other.x;
          //  etc...
      }

Then derived classes can call the super's copy in their copy:

      void copy(DerivedA other) {
           super.copy(other);
           // copy my derived fields
      }

and dup at every level can call copy:

     DerivedA dup() {
        auto ret = new DerivedA();
        ret.copy(this);
        return ret;
     }


So is this a good way to do it?  It seems pretty simple and 
straightforward, but I'm kind of nervous about the whole area of copying 
because I know there's volumes written about it in C++.  I'm sure I 
don't recall all the ins and outs of everything I've read about doing 
copying in C++.  But maybe there are just fewer gotchas in D.

Also I'm curious to know if there are any emerging trends on what to 
call the copy member function because life is better if we don't all 
invent our own convention.

--bb


More information about the Digitalmars-d-learn mailing list