&this pointer
Bill Baxter
dnewsgroup at billbaxter.com
Sat Feb 10 15:22:36 PST 2007
By reference it means that 'this' already *is* a pointer.
You don't need to take it's address. If you do you're just getting the
address of the pointer not the address of the object.
Try something like
writefln("%x",cast(void*)this);
if you really want to see the address of the object.
--bb
e-t172 wrote:
> Hi,
>
> I'm a beginner with D, I've got some basis with C/C++ but I mainly
> program with PHP. Ad far as I'm concerned, D is a very interesting
> language, hence I started to develop a personal project in D to get a
> clear idea of its features ; nonetheless, during my research, 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, so coherently, &this should return the memory
> address of the object itself.
>
> It that is correct, could one explain that to me (compiled with DMD 1.0) :
>
> ---
>
> import std.stdio;
> import std.string;
>
> class Test
> {
> this()
> {
> writefln("in this() itself - &this : ", &this);
>
> foo("called from this(), first shot");
> foo("called from this(), second shot");
> }
>
> void foo(char[] location)
> {
> writefln(location, " - foo() - &this : ", &this);
>
> bar(location);
> }
>
> void bar(char[] location)
> {
> writefln(location, " - bar() - &this : ", &this);
> }
> }
>
> int main()
> {
> auto test = new Test();
>
> test.foo("called from main(), first shot");
> test.foo("called from main(), second shot");
>
> return 0;
> }
>
> ---
>
> $ ./test
> in this() itself - &this : BFAE4394
> called from this(), first shot - foo() - &this : BFAE4370
> called from this(), first shot - bar() - &this : BFAE4344
> called from this(), second shot - foo() - &this : BFAE4370
> called from this(), second shot - bar() - &this : BFAE4344
> called from main(), first shot - foo() - &this : BFAE438C
> called from main(), first shot - bar() - &this : BFAE4360
> called from main(), second shot - foo() - &this : BFAE438C
> called from main(), second shot - bar() - &this : BFAE4360
>
> ---
>
> In accordance with the output, the object location in memory endlessly
> changes ?! I admit to be a little startled...
>
> e-t172
More information about the Digitalmars-d-learn
mailing list