new returning the same memory....

drug drug2004 at bk.ru
Thu Nov 8 12:10:36 UTC 2018


08.11.2018 14:48, Codifies пишет:
> On Thursday, 8 November 2018 at 11:46:44 UTC, Codifies wrote:
>> when creating a new instance of a class
>>
>> aclass a = new aclass();
>>
>> I was under the impression that this created a new chunk of memory on 
>> the heap...
>>
>> however I'm trying to create this class instance in another classes 
>> method, I also need to store a pointer to this newly created instance 
>> in the same method.
>>
>> when I look at the actual value of the pointer, although it does 
>> change after multiple goes, frequently its the same value.
>>
>> It almost looks like its allocating on the local stack and its made a 
>> new instance thats entirely local to the factory method.
>>
>> do I need to manually allocate the memory ?? how do I do this? how can 
>> I allow the GC to clean this up?
>>
>> I'm *really* discombobulated now, as new doesn't seem to be working 
>> how I thought it did!!!
> 
> I'll try to spin up a minimal example...
You take address of local variable, not a class instance. Just use the 
var, not its address:
```
	auto a = new MyClass();
	writefln("%s", &a); // here you write to console address of local var 
a, not the class instance
	writefln("%s", cast(void*)a); // here you write to console address of 
the class instance
```


More information about the Digitalmars-d-learn mailing list