Copying reference types by value

Ali Çehreli acehreli at yahoo.com
Wed Apr 17 09:54:45 PDT 2013


On 04/17/2013 09:17 AM, Joseph Rushton Wakeling wrote:

 > Defining a .dup method doesn't seem appropriate either because 
although it
 > allows me to duplicate the values, setting
 >
 > 	a = b.dup;
 >
 > will mean that a now becomes a new object, and any other entities 
that were
 > pointing at the original a will suddenly become decoupled from its 
values.  So,
 > if I do,
 >
 > 	c = a;
 > 	a = b.dup;
 >
 > ... I will no longer have c equal to a.

I haven't used it anywhere but I did think about this very issue just 
the other day. I thought about defining a takeOver() member function 
that does what you need:

   // take over the members of b
   a.takeOver(b); // b becomes null (or .init?)

Using takeOver() along with dup(), one can copy state:

   a.takeOver(b.dup());

Of course there can be a wrapper function for that. :)

But I am curious as well. What do others do in such cases? Are there 
accepted solutions in other languages like Java and C#?

Ali



More information about the Digitalmars-d-learn mailing list