How to instantiate class object NOT in the GC heap

Alex Rønne Petersen alex at lycus.org
Sun Jul 15 06:50:57 PDT 2012


On 15-07-2012 15:43, Alexandr Druzhinin wrote:
> Hello,
>
> I need something like that -
> http://digitalmars.com/techtips/class_objects.html, but more portable. I
> saw it sometime ago, but now can not find anything.
> Could someone help me.

This is how you do it in modern D:

import core.stdc.stdlib, std.conv;

class A {}

void main()
{
     // allocate and initialize
     auto size = __traits(classInstanceSize, A);
     auto mem = malloc(size)[0 .. size];
     auto a = emplace!A(mem);

     // a is now an instance of A in the libc heap.

     // finalize and deallocate
     clear(a);
     free(mem.ptr); // or free(cast(void*)a);
}

clear() calls the finalizer on the object you give it. In the case of A, 
there is no finalizer, so it doesn't matter. It would matter if you had 
something like:

class A
{
     private void* resource;

     ~this()
     {
         freeResource(resource);
     }
}

-- 
Alex Rønne Petersen
alex at lycus.org
http://lycus.org




More information about the Digitalmars-d-learn mailing list