&this pointer

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sat Feb 10 15:24:01 PST 2007


e-t172 wrote:
> I've 
> noticed a behavior I considered very weird about the 'this' reference. 
> According to what I understood from the documentation, it is a reference 
> to the object itself,

Correct.

> so coherently, &this should return the memory 
> address of the object itself.

Wrong.
A reference in D is different from a reference in C++. If you take the 
address of a reference in D, you do not get the address of the object 
referenced, but the address of the reference itself.
Think of a D reference as a pointer to the body of the class, with small 
differences. For one, casting between references works differently. For 
another, pointer arithmetic doesn't work on references. But operators 
like (unary) & work the same: in this case, it returns a pointer to the 
memory storing the address being referred to.

To get the address of the object from a reference you can cast it to 
void*. So in your case, replace "&this" with "cast(void*)this" and you 
will see the same address everywhere.


More information about the Digitalmars-d-learn mailing list