&this pointer

e-t172 idontlikespam at nospam.com
Sat Feb 10 15:06:12 PST 2007


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