How to instantiate class object NOT in the GC heap

Alex Rønne Petersen alex at lycus.org
Sun Jul 15 08:03:46 PDT 2012


On 15-07-2012 16:46, Alexandr Druzhinin wrote:
> 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?
>

You pass those after the 'mem' argument to emplace. So, for example:

auto a = emplace!A(mem, "foo", bar, 'b', 'a', 'z');

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




More information about the Digitalmars-d-learn mailing list