How to instantiate class object NOT in the GC heap

Alexandr Druzhinin drug2004 at bk.ru
Sun Jul 15 07:46:13 PDT 2012


15.07.2012 20:50, Alex Rønne Petersen пишет:
>
> 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);
>      }
> }
>
how to pass arguments to ctor of class A?



More information about the Digitalmars-d-learn mailing list