this as lvalue?

Jonathan M Davis jmdavisprog at gmail.com
Sun Sep 5 15:46:57 PDT 2010


On Sunday 05 September 2010 15:02:10 Andrej Mitrovic wrote:
> Does this mean assigning to fields won't be an option anymore when using
> this?
> 
> E.g.:
> 
> class Foo
> {
>     int x;
>     int y;
> 
>     void changeXY(int x, int y)
>     {
>         this.x = x;
>         this.y = y;
>     }
> }

No, it simply means that you won't be able to do this in a class:

this = new MyObj();


In C++, this is a const pointer to non-const data in non-const functions and a 
const pointer to const data in const functions. The problem is that due to how D 
deals with const and references, you can't have this be a const reference to 
non-const data. And with the current implementation, that means that you can 
reassign this. Now, that's setting a local variable, so it only affects that 
function and any other member functions that it calls, but it's still not a good 
thing. If this in classes becomes an rvalue semantically-speaking (regardless of 
how its done under the hood), then you won't be able to assign to it anymore. 
But you should still be able to assign to anything that you get from it. 
Remember that this.x is dereferencing the this reference to get at the memory 
where x is. Whether you can assign to this is irrelevant for that. It's not 
trying to do anything to this itself, just what it refers to.

- Jonathan M Davis


More information about the Digitalmars-d mailing list