Take the 2-minute tour ×

I'm learning D from 8 years in C++. My question is with regards to D garbage collection - when do I use delete, and when don't I need to?

share|improve this question
Doesn't garbage collection mean that you don't need to delete at all? –  delnan Jan 3 '11 at 22:53
add comment

2 Answers

up vote 14 down vote accepted

You don't. Delete is not to be used with D version 2 and intended to be removed from the language. What the hold up is, I am not sure. Instead you use a function, destroy(object), which calls the destructor where you can free resources that are not GC memory. The destructor will be caused again during GC collection of the objects own memory. This is explained in "The D Programming Language".

The idea is to reclaim resources earlier than what the GC would provide and prevents memory corruption from dangling pointers. To be less safe the core.memory module provides GC.free(object) which can be used to free the memory, after calling destroy(object).

As I'm not a C++ programmer, I don't really know the RAII pattern, but this and reference counting is the expected strategy if you wish to avoid the GC.

share|improve this answer
Yes. clear() is used to call an object's destructor and put it in an invalid state, but it's still the GC's job to reclaim the memory. delete is going away completely. If you want to completely manage memory yourself, you use malloc and free. However, using clear(), malloc, and free in D code really shouldn't be the norm. They're there for those special cases where you need them. –  Jonathan M Davis Jan 4 '11 at 4:01
Thank you Jonathan, I didn't mean to imply that it would be common to use such a pattern. Only that this is the facility to do it. Which makes Corbin March's a better answer since the question really wasn't about delete itself. –  he_the_great Jan 4 '11 at 16:39
add comment

Take a look at Garbage Collection in the D documentation. As noted, it is (almost) never necessary to explicitly manage memory. Of course after spending a handful of bullet points trying to convince you of the GC's power, they include a few scenarios where garbage collection falls short. To address these short-falls (they call them constraints), Digital Mars offers tips for Memory Management.

If possible, let the D garbage collector do its thing. Ignore explicit memory management. In a few very specific scenarios, there's a potential for an unacceptable GC pause or memory that can't be reclaimed. If your app includes one of these scenarios (test and profile to prove it), isolate the cause of the problem and explicitly manage memory where necessary. D lets you start as an optimist. If things don't work out perfectly, it's reassuring that you can fall back on explicit memory management.

share|improve this answer
Thanks - I'd looked through the garbage collection documentation, but it didn't feel clear enough for me to make any assumptions. –  RobotGymnast Jan 4 '11 at 0:50
add comment

Your Answer


