&this pointer
Derek Parnell
derek at psych.ward
Sun Feb 11 12:34:53 PST 2007
On Sun, 11 Feb 2007 21:14:26 +0100, e-t172 wrote:
> The following does not work :
>
> import std.stdio;
>
> class Test
> {
> this()
> {
> void* ptr = cast(void*) this;
>
> (*(cast(Test*) ptr)).foo();
> }
>
> void foo()
> {
> writefln("OK");
> }
> }
>
> int main()
> {
> auto test = new Test();
>
> return 0;
> }
>
> Result : segmentation fault
>
> Could one explain why ?
You need "(cast(Test) ptr).foo();" instead.
This is because 'void* ptr' contains the address of the object, and when
calling object members, you need to use a /reference/ to the object and not
the object itself. Casting 'ptr' to 'Test*' just tells the compiler to
assume that 'ptr' points to a Test object and then using the '*' operator
returns the object and not a reference to the object.
If, however you had cast 'ptr' to just a 'Test', this tells the compiler to
assume that 'ptr' contains a reference to the object and so it can then
find the member to invoke.
--
Derek Parnell
Melbourne, Australia
"Justice for David Hicks!"
skype: derek.j.parnell
More information about the Digitalmars-d-learn
mailing list