Copying reference types by value

Ali Çehreli acehreli at yahoo.com
Wed Apr 17 13:29:21 PDT 2013


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

 > On 04/17/2013 06:54 PM, Ali Çehreli wrote:
 >> 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?)
 >
 > Ahh, so you mean that the current members of a get discarded and 
replaced with
 > those of b?

Yes but as I said I am not sure how useful or needed this whole thing is.

The language handles copy, move, and assignment for structs. takeOver() 
seems to be a primitive operation for classes.

 >> Using takeOver() along with dup(), one can copy state:
 >>
 >>    a.takeOver(b.dup());
 >>
 >> Of course there can be a wrapper function for that. :)
 >
 > It's an intriguing thought.  How do you get round the issue of 
private variables
 > ... ?

takeOver()'s parameter is presumably the same type as the class's so the 
private members are accessible. Of course any member may be well 
encapsulated; then, takeOver() depends on similar functionality that 
those members provide, perhaps through member functions that are again 
named takeOver() but there is no standard for it.

A framework may require that such "take over" member functions should be 
marked by a specific UDA.

 >  And what's the benefit over a method like, say,
 >
 > 	a.copyFrom(b);

That's what I meant by "a wrapper function." But I think move is a more 
fundamental operation that elides a copy. If we had only copyFrom(), 
then the following would indeed need to copy:

     // foo() returns a class object
     a.copyFrom(foo());

On the other hand, takeOver() would have the ability to move the members 
of the returned rvalue object without needing to copy.

 > ... which just copies values between corresponding variables? 
(Leaving aside
 > that takeOver has applications of its own -- I mean my question 
purely in the
 > context of copying values.)

Agreed.

Ali



More information about the Digitalmars-d-learn mailing list