Taking a copy of an object

Derek Parnell derek at nomail.afraid.org
Thu Aug 3 17:55:48 PDT 2006


On Thu, 03 Aug 2006 16:28:25 -0700, Kirk McDonald wrote:

> People used to C++ are used to doing this with an operator overload. 
> People used to some other languages (e.g. Python) will be more used to 
> using a method (or even a library function, in the case of Python). I 
> honestly don't think it matters.
> 
> One could also argue for the use of copy constructors, of course. This 
> may be getting too close to C++ for some people's tastes, though. (The 
> syntax is also more verbose than a simple .dup property.)

Copy constructors and 'standard' functions would have to work with basic
types, structs and arrays too for it to be really useful.

 
> class Foo {
>      int m_i;
>      this(int i) { m_i = i; }
>      this(Foo f) { m_i = f.m_i; }
> }
> 
> Foo a, b;
> a = new Foo(20);
> b = new Foo(a);
> 
> This does have the advantage of using "new" to make it clear that we are 
> allocating a new object (though I don't think this is really a problem 
> with just using .dup).
> 
> With reflection support, we could even give Object a useful default copy 
> constructor, as Tom S pointed out.

Not everything is an object. <g>

  template backup(T)
  {
      void backup(inout T[] st, T dt)
      {
           st.length = st.length + 1;
           st[$-1] := dt;  // Invokes opDup for classes and structs,
                           // .dup for arrays,
                           // binary copy for everything else
      }
  }

  int[] istore;
  backup( istore, anInt);

  Foo[] foostore;
  backup( foostore, aFoo);
 

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
4/08/2006 10:40:00 AM



More information about the Digitalmars-d mailing list