Duplicating multidimensional array
Ali Çehreli
acehreli at yahoo.com
Thu May 30 20:27:43 PDT 2013
On 05/30/2013 04:48 PM, Ali Çehreli wrote:
> For classes, there is no syntax for copying. The type may have annotated
> a member function that it is the duplication function or we may know by
> convention that dup() is the equivalent of array .dup.
Kenji Hara responded to another thread on the main D newsgroup.
Apparently, such a convention-based functionality is already being used
by std.conv.to. Here is the excerpt:
On 05/30/2013 07:13 PM, Kenji Hara wrote:
> Current D does not provide generic way for deep copy of class object.
> But, you can use std.conv.to with adding a kind of copy constructor.
>
> class C
> {
> int x;
> this(int n) { x = n; }
>
> // Do deep copy, this is used by to!(array-type)(array)
> this(const C c) { this.x = c.x; }
> }
> void main()
> {
> const(C)[] carr = [new C(1), new C(2)];
> // C[] marr = carr.dup;
> // --> Error: cannot implicitly convert element type const(C) to
> mutable in carr.dup
>
> import std.conv;
> C[] marr = carr.to!(C[]);
> // For class arrays which need copy elements,
> // std.conv.to returns [new C(carr[0]), new C(carr[1]), ...]
>
> // modify element of returned array
> marr[0].x = 5;
>
> // Right now carr[0] and marr[0] are completely unrelated objects
> assert(carr[0].x == 1);
> assert(marr[0].x == 5);
> }
>
> Kenji Hara
Ali
More information about the Digitalmars-d-learn
mailing list