Ref and class function calls?

John Colvin john.loughran.colvin at gmail.com
Tue Apr 16 07:33:20 PDT 2013


On Tuesday, 16 April 2013 at 05:37:48 UTC, Tofu Ninja wrote:
> I could not think of what to call this because I don't know if 
> it has a name to call it by.
>
> Basicly what I was wondering is if their was a way in D to make 
> a class function pass the object being called on by reference.
>
> might be easier to show code, basically I want something like 
> this to be possible
>
> class A
> {
>      //some how signify that this function passes 'this' by 
> reference
>      public void replace()
>      {
>           this = new A();
>      }
> }
>
> ...
>
> A a = new A();
> A b = a;
> b.replace();
> assert(b != a);
>
> I don't know if I am being clear or if their is something 
> better to call this.
>
> Thanks for the help
> Tofu

A member function cannot modify it's own 'this' pointer.

However, a free function can do it happily, which when combined 
with UFCS gives you the same syntax and behaviour:

class A {
	//......
}

void replace(ref A a)
{
	a = new A();
}

void main() {
	A a = new A();
	A b = a;
	assert(b is a);
	b.replace();
	assert(!(b is a));
}

http://dpaste.dzfl.pl/147f69e1


More information about the Digitalmars-d-learn mailing list