Manual memory management in D2
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Tue Jul 13 13:16:30 PDT 2010
On 07/13/2010 01:59 PM, Vladimir Panteleev wrote:
> On Tue, 13 Jul 2010 21:36:02 +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.
>> But manual deletion has no business in the garbage collected heap.
>
> Isn't that making the assumption that all D programs are garbage-collected?
No. It is not making that assumption.
>> That currently druntime provides it is an accident caused by
>> thecurrent implementation; most GC's cannot provide efficient manual
>> reclamation. And they shouldn't anyway.
>
> Why not? And what if I don't use the GC (just the
> allocation/deallocation aspects of it)?
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.
>> (There's a longer discussion underneath this concerning what memory
>> really is and what GCs really are and do.)
>
> I understand your points regarding leaving deallocation to happen on a
> GC run being more efficient than manually deallocating objects
> individually,
I didn't make that point.
> but this doesn't cover all use-cases. Also, what if I need
> to deallocate a large block of memory right now? I'd be forced to use
> the more verbose and less safe "free" functions.
To manually manage a large memory block, you may want to use malloc()
and free(). Again: manual free() should NOT be counted on in a garbage
collector.
Andrei
More information about the Digitalmars-d
mailing list