Can't understand if deallocation happens?

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 22 06:28:54 PST 2017


On Sunday, 22 January 2017 at 14:04:55 UTC, Suliman wrote:
> So str.ptr is just shortcut?

str.ptr is the actual member. In D, pointers to structs (and an 
array is virtually the same as a struct) will automatically 
dereference themselves.

T* t;
t.member; // automatically rewritten into (*t).member)


Your str_ptr variable in this code is completely useless and 
should be removed. It's presence only confuses you.

> Ok, but how to free memory from first located value (from 
> `aaa`)?

Supported answer: you don't, it has infinite lifetime and you're 
claiming it is immutable, but then trying to pull the memory out 
from under it! The supported solution is simply to let the 
garbage collector manage it.

But..

>     //GC.free(str_ptr.ptr); // Error: function 
> core.memory.GC.free (void* p) is not callable using argument 
> types (immutable(char)*)


If you must call the function though, you can simply `cast(void*) 
str.ptr`, or use `char[]` up above instead of `string` when 
declaring it, so it has a mutable pointer to begin with. Since 
you are using .dup anyway, both declarations are equally legal.



More information about the Digitalmars-d-learn mailing list