Array of class intances

lutger lutger.blijdestijn at gmail.com
Tue Apr 8 07:47:52 PDT 2008


YY wrote:

> Suppose I have a class :
> 
> class C {
>   int a;
>   int b;
>   this(int a1, int b1) {
>     a = a1;
>     b = b1;
>   }
> }
> 
> And I want to make an array of class C instances :
> 
> C[] inst;
> inst ~= new C(1,2);
> inst ~= new C(3,4);
> 
> What happened if I make a copy of inst using dup? Are the values or the
> pointers are copied?

The values are copied. But the values in this case are Objects, which are
always pointers under the hood. So in the end pointers are copied by
value ;) 

> C[] copyinst = inst.dup;
> 
> When I tried to assert(inst.ptr == copyinst.ptr) it fails, which means it
> copies the contents.

'inst.ptr == copyinst.ptr' compares the adressess of the arrays themselves,
independent of their content. It means the arrays are stored in different
place in memory, but the content can still be the same. 
Try this:  inst[0] == copyinst[0]  // true
and this: &inst[0] == &copyinst[0] // false
 
> But when I do this :
> 
> inst.a += 3;
> assert(inst.a != copyinst.a);
> 
> It also fails.
> 
> What's the best method to copy (clone) array of instances?

There is no standard way, perhaps somebody has written something?

If haven't found a need for this myself yet, I prefer to use structs is
these cases. You could implement an .dup or .clone method in your classes
and create such a functions yourself, something like this (caution, not
tested):

 T[] dup(T)(T[] a)
 {
    static if (is(typeof(T.dup)))
    {
        T[] result;
        result.length = a.length;
        foreach(i, val; a)
            result[i] = val.dup;
        return result;
    }
    else
        return a.dup;
 }







More information about the Digitalmars-d-learn mailing list