Manual memory management in D2

Vladimir Panteleev vladimir at thecybershadow.net
Tue Jul 13 14:15:19 PDT 2010


On Tue, 13 Jul 2010 23:16:30 +0300, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

>>> Not quite. New is different because it is a primitive - it can't be
>>> implemented as a function (well it could if it user placement new, but
>>> we're back to square one). In contrast, delete already knows the type
>>> of the object it's destroying and can call the destructor manually so
>>> it is easy to implement as a regular function.
>>
>> Sorry, not following you here. Why can't new be implemented as a
>> templated function which takes the type of the object to create as a
>> template parameter? Isn't it just allocation, copying over T.init, then
>> calling the constructor with whatever arguments the user passed?
>
> In D it's possible to call the constructor by issuing __ctor(). In C++  
> there is no way, hence the presence of a language primitive.

Doesn't that only support my argument that new *can* be implemented as a  
function?

> You should use malloc() and free() for manual memory management and the  
> GC for automatic memory management. Each of these two is ill-suited for  
> carrying the other's job.

Thanks, that was really what I was missing from the picture.

However, D allows overloading new/delete for custom allocators[1] - this  
can be used for a cleaner way to allocate objects in unmanaged memory. I  
don't see why this use of the delete keyword should be deprecated.

   [1]: http://digitalmars.com/d/2.0/memory.html#newdelete

-- 
Best regards,
  Vladimir                            mailto:vladimir at thecybershadow.net


More information about the Digitalmars-d mailing list