Taking a copy of an object

Dave Dave_member at pathlink.com
Fri Aug 4 07:04:41 PDT 2006


kris wrote:
> Derek Parnell wrote:
>> On Thu, 03 Aug 2006 23:47:47 -0700, kris wrote:
>>
>>
>>> Does deep-copy really need an operator? I have to wonder whether a 
>>> simple naming-convention would do the trick instead  ... that way, 
>>> you'd never have a /default/ deep-copy, and usage mistakes would 
>>> produce a most welcome compile-time error.
>>
>>
>> I'm not asking for a default deep copy. If you haven't defined one 
>> then its
>> a compile time error. How would a function/method work with arrays as 
>> .dup
>> only does a shallow copy. And how would it work in templates that use 
>> basic
>> types? An operator overcomes these issues by letting the compiler know 
>> what
>> the coder's intentions are and generate code accordingly. 
> 
> True. If I have an array of char*, an array of class refs, or something 
> similar, and want a deep copy, then an operator might be a fair option. 
> But so would the ability to add methods to arrays (for example), which 
> would be far more powerful (and competitive with C#) than one specific 
> deep-copy facility.
> 
> On the other hand, one has to wonder how often deep copy is actually 
> used? In 22 years of paid R&D (pretty much across the spectrum too) I 
> can recall using deep-copy perhaps less than half a dozen times? As 
> operations go, it's typically a rather expensive one. Most folk seem to 
> try and find a way around that instead? Certainly it might be nice to 
> have, but is it really more important than, say, fixing static-arrays?
> 
> You didn't say that, or rank deep-copy in any way, but one has to wonder?
> 
> 
> All that aside, .dup() is still a better approach for shallow copy :)

With all that in mind - if .dup was given an op overload for classes and structs, couldn't that then 
be used to do the deep copy when it was imperative?

For example:

class C // built-in .dup copies i and the reference to str
{
     int i;
     char[] str;
}

class D // .dup is overloaded to do a default shallow and optional deep copy
{
     int i;
     char[] str;
     C opDup(bool deep = false)
     {
         C c = new C;
         c.i = this.i;
         if(deep)
             c.str = this.str.dup;
         else
             c.str = this.str;
         return c;
     }
}

- Dave



More information about the Digitalmars-d mailing list