Manual memory management in D2

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Jul 12 07:19:26 PDT 2010


On 07/12/2010 03:01 AM, Robert M. Münch wrote:
> On 2010-07-12 05:03:06 +0200, Petr said:
>
>> Ok, so I now know how to explicitly free memory allocated to the GC
>> heap. Now the question is, should we have the usual C* c = new C(),
>> and I wanted to allocate it to unmanaged memory(just like it would in
>> C++) and then at some
>> point call the destructor on it and free the memory, outside of the
>> GC. How would I do that?
>
> Yes, that's something I need to, because I need to allocate memory from
> a special pool, the GC doesn't know about. And I need to handle freeing
> of such a memory myself because it's persistent and surviving
> application start-overs.

Say your allocator's interface is:

void[] AllocateStuff(size_t size);
void DeallocateStuff(void* p);

Then you'd write these two helper functions to create and dispose objects:

T * myMake(T)() if (is(T == struct))
{
     auto buf = AllocateStuff(T.sizeof);
     return emplace!T(buf);
}

T myMake(T)() if (is(T == class))
{
     auto buf = AllocateStuff(__traits(classInstanceSize,T));
     return emplace!T(buf);
}

void myDelete(T)(T p)
{
     clear(p);
     DeallocateStuff(p);
}

emplace(), defined in std.conv, is relatively new. I haven't yet added 
emplace() for class objects, and this is as good an opportunity as any:

http://www.dsource.org/projects/phobos/changeset/1752


Andrei


More information about the Digitalmars-d mailing list