Call destructor directly.

Benjamin Thaut code at benjamin-thaut.de
Mon Oct 21 04:48:11 PDT 2013


Am 21.10.2013 04:17, schrieb Adam D. Ruppe:
> On Monday, 21 October 2013 at 02:06:02 UTC, Agustin wrote:
>> I'm implementing some custom memory allocator, is possible to call an
>> object destructor directly?
>
>
> destroy(object);
>
> destroy is in the automatically imported object.dm so you don't have to
> import anything,
>
> The source code is in dmd2/src/druntime/src/object_.d, there's a few
> overloads if you are curious how it is implemented. Short answer is
> there's a pointer to the destructor in the TypeInfo and destroy calls it.

Using destroy will zero the entire memory block after destroying the 
object. If you are freeing the memory right after destroying this is 
going to cost you performance.

To avoid this declare:

extern (C) void rt_finalize2(void* p, bool det = true, bool resetMemory 
= true);

and then call

rt_finalize(cast(void*)object, false, false);

Also if you want to give a nice error message in case you are calling a 
construcor that does not exist you should take a look at my AllocatorNew 
function:

https://github.com/Ingrater/druntime/blob/merge64/src/core/allocator.d#L616

Doing it the way emplace does will just result in a error message

"Dont know how to initialize a object of type YourObject"

With some meta programming you can get error messages like:

"Dont know how to initialize a object of type YourObject
Available constructors:
this(int, int)
this(float)
this(void*)"

Kind Regards
Benjamin Thaut


More information about the Digitalmars-d-learn mailing list