Implementing .dup / clone for class hierarchies

Bill Baxter dnewsgroup at billbaxter.com
Sun Dec 16 13:26:02 PST 2007


guslay wrote:
> Bill Baxter Wrote:
> 
>> 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?
>>
> 
> I came across this thread the other day, that suggest doing bitwise copy of the class for shallow copying. I don't know how safe that is.
> 
> http://www.digitalmars.com/d/archives/digitalmars/D/learn/1625.html
> 
> 
> Another thread that caught my attention was this one.
> 
> http://www.digitalmars.com/d/archives/digitalmars/D/41145.html#N41264
> 
> 
> Those threads are a little old. I too would like to know if someone came up with a state of the art solution or an informal naming convention.
> 
> 

Good sleuth work!
Ha, looks like I posted a message on that second thread.  And created a 
wiki page!  Totally forgot about that.  Hence we see the futility of 
creating wiki pages.  :-)

Also see the recent thread over on digitalmars.D called "what was wrong 
with struct & class in C++"

For some reason everyone seemed to like Mikola's suggestion of 'clone' 
for deep copy and 'dup' for shallow copy, but the odd thing about that 
is that .dup on built-in arrays is a deep copy.  So it seems it should 
mean a deep copy for classes too.  Bad idea to go out of your way to 
mimic the syntax of D built-ins but give it a different meaning, IMHO.


The first thread is more about automatic shallow copying and Burton 
Radons came up with this compiler-specific hack:
"""
      private extern (C) Object _d_newclass (ClassInfo info);

      Object shallow_copy (Object value)
      {
          if (value is null)
              return null;

          void *copy = _d_newclass (value.classinfo);
          size_t size = value.classinfo.init.length;

          copy [8 .. size] = (cast (void *) value) [8 .. size];
          return cast (Object) copy;
      }

Better to start at that offset to avoid copying the synchronisation
handle over, plus it's pointless work.
"""

That makes me shudder.  But it wouldn't be fine if it were implemented 
as part of object.d.  I think that functionality would actually be very 
useful to have as member of ClassInfo.  Then a base class .dup function 
could shallow copy everything first so that derived .dups that only add 
value members wouldn't need to do anything.

--bb


More information about the Digitalmars-d-learn mailing list