On Wednesday, 27 January 2016 at 06:40:00 UTC, Basile B. wrote:
On Tuesday, 26 January 2016 at 01:09:50 UTC, Igor wrote:
Is there any examples that shows how to properly allocate an
object of a class type with the new allocators and then
release it when desired?
This is more or less the same answer as you've get previously
except that I don't use emplace but rather a copy of what's
done in _d_new_class() from the D runtime:
CT construct(CT, A...)(A a) @trusted @nogc
if (is(CT == class))
{
import std.experimental.allocator.mallocator;
auto size = typeid(CT).init.length;
auto memory = Mallocator.instance.allocate(size); // D
runtime use GC here
memory[0 .. size] = typeid(CT).init[];
static if (__traits(hasMember, CT, "__ctor"))
(cast(CT) (memory.ptr)).__ctor(a);
import core.memory: GC;
GC.addRange(memory.ptr, size, typeid(CT));
return cast(CT) memory.ptr;
}
the GC stuff could look superfluous but without this and if
there's a GC allocated members in your class (even a simple
dynamic array) then you'll encounter random errors at run-time.
Thanks.
But doesn't this ultimately defeat the purpose of having manual
memory management if one has to add it to the GC to be scanned?
Seems like it is just an extra step. The whole point is to
prevent the GC from having to mess with the object in the first
place. I understand if it uses GC based objects then the GC needs
to be informed but this really feels like it defeats the purpose.
Ultimately I want no GC dependency. Is there an article that
shows how this can be done?