Array of class intances

Regan Heath regan at netmail.co.nz
Tue Apr 8 07:25: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?
> 
> C[] copyinst = inst.dup;
> 
> When I tried to assert(inst.ptr == copyinst.ptr) it fails, which means it copies the contents.

This assert tells you that the data pointer of the arrays is not equal, 
which means each array has it's own copy of the class references.

But, it doesn't mean the class instances themselves have been duplicated.

This shouldn't fail:

assert(inst[0] == copyinst[0]);

meaning the first item in each array is the same reference, you can see 
the value of the reference by doing this:

writefln("%x", cast(void*)inst[0]);
writefln("%x", cast(void*)copyinst[0]);

> But when I do this :
> 
> inst.a += 3;
> assert(inst.a != copyinst.a);
> 
> It also fails.

That is because inst[0] and copyinst[0] both refer to the same class 
reference, therefore inst[0].a is the same variable as copyinst[0].a

> What's the best method to copy (clone) array of instances?

Add this method to your class C

   C dup()
   {
   	return new C(a,b);
   }

Then, instead of this:

C[] copyinst = inst.dup;

use:

C[] copyinst;
foreach(i; inst)
	copyinst ~= i.dup;

Regan


More information about the Digitalmars-d-learn mailing list