deprecated delete and manual memory management

Daniel Gibson metalcaedes at gmail.com
Tue Apr 26 14:01:58 PDT 2011


Am 26.04.2011 21:48, schrieb Benjamin Thaut:
> Am 26.04.2011 21:26, schrieb Daniel Gibson:
>> Am 26.04.2011 20:23, schrieb Steven Schveighoffer:
>>> On Tue, 26 Apr 2011 14:14:11 -0400, Benjamin Thaut
>>> <code at benjamin-thaut.de>  wrote:
>>>> Could someone please write a small example how manual memory
>>>> management would look without new / delete?
>>>
>>> I think that is a good idea.
>>>
>>
>> Not a tutorial, just a simple example using C malloc/free:
>> http://pastebin.com/HSBrk5kA
>>
>> Cheers,
>> - Daniel
> 
> Thanks for the example, thats exactly what I needed.
> 
> I still don't understand why the delete operator is deprecated
> completely. It could be defined, that it is only useable if the new and
> delete operator have been overloaded in the class or struct that is
> tried to be deleted.
> 

This way it's much more flexible. Note that you don't have to change the
classes at all (i.e. you don't have to provide new() and delete()) to
use a custom allocator. This means
1. you can use custom allocators with classes you didn't write yourself
2. you can even use different custom allocators for the same class at
the same time (you'd have to be really careful not to screw that up by
using the wrong deallocator for an Object)
3. you only have to write an (de)allocator once and you can use it for
any class, even if they're not derived from each other

Also, and I think this is really a great feature for performance that
isn't available with overloaded new and delete operators, you can create
an array of objects that really lie next to each other in memory (like
an array of structs), so you can benefit from CPU cache effects.

This is a very simple example doing that: http://pastebin.com/98mGU7y1
However you have to be careful with it if, i.e. don't put new objects in
it, don't slice it (you have to at least feed the original array to
myDeleteArr()) etc.
To really use something like this probably a struct that enforces this
(by conservatively overloading opIndex, opAssign etc) would be better
than a function returning a dynamic array that happens to point to
objects that are adjacent in memory.

Cheers,
- Daniel


More information about the Digitalmars-d mailing list