Best memory management D idioms

Eugene Wissner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 7 10:21:43 PST 2017


On Tuesday, 7 March 2017 at 17:37:43 UTC, XavierAP wrote:
> On Tuesday, 7 March 2017 at 16:51:23 UTC, Kagamin wrote:
>> There's nothing like that of C++.
>
> Don't you think New/Delete from dlib.core.memory fills the 
> bill? for C++ style manual dynamic memory management? It looks 
> quite nice to me, being no more than a simple malloc wrapper 
> with constructor/destructor calling and type safety. Plus 
> printMemoryLog() for debugging, much easier than valgrind.
>
>> do you want to manage non-memory resources with these memory 
>> management mechanisms too?
>
> I wasn't thinking about this now, but I'm sure the need will 
> come up.

Yes. For simple memory management New/Delete would be enough. But 
you depend on your libc in this case, that is mostly not a 
problem. From experience it wasn't enough for some code bases, so 
the C-world invented some work arounds:

1) Link to an another libc providing a different malloc/free 
implementations
2) Use macros that default to the libc's malloc/free, but can be 
set at compile time to an alternative implementation (mbedtls 
uses for example mbedtls_malloc, mbedtls_calloc and mbedtls_free 
macros)

To avoid this from the beginning, it may be better to use 
allocators. You can use "make" and "dispose" from 
std.experimental.allocator the same way as New/Delete.

I tried to introduce the allocators in dlib but it failed, 
because dlib is difficult to modify because of other projects 
based on it (although to be honest it was mostly a communication 
problem as it often happens), so I started a similar lib from 
scratch.


More information about the Digitalmars-d-learn mailing list