Ref and class function calls?

Ali Çehreli acehreli at yahoo.com
Tue Apr 16 14:14:15 PDT 2013


On 04/16/2013 08:44 AM, Tofu Ninja wrote:

 > On Tuesday, 16 April 2013 at 15:27:10 UTC, Ali Çehreli wrote:
 >> On 04/16/2013 07:57 AM, Tofu Ninja wrote:
 >> It would be bad design if a class variable decided to refer to another
 >> object without the owner of that variable knowing about it.
 >
 >
 > I don't know, It seems like the caller of the function should know what
 > he/she is calling. I don't make practice of calling a function with out
 > knowing what it will do first, the caller should know that their is a
 > chance the variable would be reassigned if its a 'ref this function'.

You are right.

I think the problem then is that 'this' is yet another handle to the 
object. Changing it wouldn't make any effect on the outside world:

   auto a = new Class();
   auto b = a;             // now two handles
   b.foo();  // let's assume that foo can assign to 'this'

When that happens, would you expect a and b also become handles to the 
new object? It could I guess, but it sounds impractical in a system 
language. The runtime does not maintain a record of what handles share 
the same object.

 > The same thing can be said about normal ref arguments. The caller knows
 > that if they pass a variable into a function that has a ref argument,
 > then there's a chance that the variable will be reassigned. Its the
 > responsibility of the caller to know what they are calling and what
 > might happen because of it.

Agreed.

 > And their are plenty of cases that a 'ref this function' is desirable.
 > Simple example, a linked list head with a push function. It reassigns
 > the head variable to what you are pushing and chains the rest after it.

What happens to other references to the old head? Do they continue 
pointing at the neck? Maybe that is understandable...

 > It makes logical sense to be able to do head.push(...)

I can't see it that way yet.

 > and it makes
 > sense for this to be a class function.

And it wouldn't make sense if it were a non-member function? If so, I 
don't see it yet.

 >
 > Tofu

Ali



More information about the Digitalmars-d-learn mailing list