www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Get address of object in constructor.

reply MGW <mgw yandex.ru> writes:
I want to get address of object Cfoo in constructor. Whether it 
is possible?

now:
-------------
class Cfoo {
	void* adrThis;
	void saveThis(void* adr) {	adrThis = adr; }
}
...
Cfoo foo = new Cfoo(); foo.saveThis(&foo);

shall be
--------------
class Cfoo {
	void* adrThis;
	this() {
		adrThis = ?????????
	}
}
...
Cfoo foo = new Cfoo();
Mar 13 2016
next sibling parent reply WebFreak001 <janju007 web.de> writes:
On Sunday, 13 March 2016 at 15:43:02 UTC, MGW wrote:
 I want to get address of object Cfoo in constructor. Whether it 
 is possible?
class Cfoo { void* adrThis; this() { adrThis = cast(void*) this; } } ... Cfoo foo = new Cfoo(); "this" should work (pun intended)
Mar 13 2016
parent MGW <mgw yandex.ru> writes:
On Sunday, 13 March 2016 at 15:49:20 UTC, WebFreak001 wrote:
 On Sunday, 13 March 2016 at 15:43:02 UTC, MGW wrote:
 I want to get address of object Cfoo in constructor. Whether 
 it is possible?
class Cfoo { void* adrThis; this() { adrThis = cast(void*) this; } } ... Cfoo foo = new Cfoo(); "this" should work (pun intended)
Super! Ok!
Mar 13 2016
prev sibling parent reply WebFreak001 <janju007 web.de> writes:
On Sunday, 13 March 2016 at 15:43:02 UTC, MGW wrote:
 Cfoo foo = new Cfoo(); foo.saveThis(&foo);
However note that this is not the same as that function. cast(void*)this and &this are 2 different things. So if you want to do the same as saveThis just do void* thisAddr = cast(void*) &this; instead
Mar 13 2016
parent reply MGW <mgw yandex.ru> writes:
On Sunday, 13 March 2016 at 16:02:07 UTC, WebFreak001 wrote:
 However note that this is not the same as that function. 
 cast(void*)this and &this are 2 different things. So if you 
 want to do the same as saveThis just do void* thisAddr = 
 cast(void*) &this; instead
void* thisAddr = cast(void*) &this; Error compile: Deprecation: this is not an lvalue
Mar 13 2016
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Sunday, 13 March 2016 at 16:16:55 UTC, MGW wrote:
 void* thisAddr = cast(void*) &this;
This doesn't really make sense anyway, this is a local variable, you want to do cast(void*) this in a class if you need the address (which btw, you shouldn't actually, the reference itself ought to be enough)
Mar 13 2016