Using the delete Keyword /w GC

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 25 12:54:57 PDT 2014


On Monday, 25 August 2014 at 17:20:20 UTC, Brad Anderson wrote:
> On Monday, 25 August 2014 at 17:10:11 UTC, Etienne wrote:
>> People have been saying for quite a long time not to use the 
>> `delete` keyword on GC-allocated pointers.
>>
>> I've looked extensively through the code inside the engine and 
>> even made a few modifications on it/benchmarked it for weeks 
>> and I still can't see why it would be wrong. Wouldn't it help 
>> avoid collections and make a good hybrid of manual 
>> management/collected code? The free lists in the GC engine 
>> look quite convenient to use. Any ideas?
>
> delete was deprecated because it is memory unsafe (there may 
> still be references to the memory). You can still use GC.free() 
> to free the memory but it must only be used with care.
>
> I feel if you are managing delete yourself you might as well 
> manage allocation yourself too and take pressure off the GC. If 
> you are sure you have only one reference and GC.free() is safe, 
> Unique was probably a better choice anyway.

Actually, delete hasn't technically been deprecated yet even 
though it was supposed to be, which is part of the problem. If it 
were, presumably folks would stop using it.

But yeah, the key problem is that deleting GCed memory is 
inherently unsafe. You can get away with it if you know for sure 
that there are no other references to that object, but if you 
screw it up, nasty things will happen. Normally, using the GC is 
supposed to guarantee memory safety, and freeing GC memory 
yourself negates that.

And as you point out, you really don't gain much by using the GC 
if you're going to be deleting stuff yourself. At that point, you 
might as well be managing the memory yourself. The main 
impediment there is the fact that we don't currently have a nice 
way to construct objects on the heap without new. After the 
memory is malloced, you need to use emplace to construct the 
object in that memory, and that gets complicated. However, once 
we have the custom allocators, that problem should go away, 
because then we should be able to do something like

auto foo = alloc.foo!Foo(arg1, arg2);

and all of the emplace pain will be dealt with for you. So, until 
we have that, I can see why someone would want to use delete, but 
it's inherently unsafe, and we really need to get it deprecated 
and then removed.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list