Alternative Memory Management in D

Reaching C++ level of abstraction

import dlib.core.memory;void main()
{
int[] array = New!(int[])(100);
Delete(array);

MyClass obj = New!MyClass(1, 2, 3);
Delete(obj);
}

Allocators

import dlib.core.memory;
import dlib.memory.gcallocator;
void main()
{
Allocator defaultAllocator = globalAllocator;
globalAllocator = GCallocator.instance;
// ‘New’ will use GCallocator

globalAllocator = defaultAllocator;
// ‘New’ will again use default allocator based on malloc
}

Ownership

import dlib.core.memory;
import dlib.core.ownership;
class MyClass: Owner
{
this(Owner owner = null)
{
super(owner);
}
}
void main()
{
MyClass c1 = New!MyClass();
MyClass c2 = New!MyClass(c1);
Delete(c1); // c2 is deleted automatically
}
class MyClass: Owner
{
//...
~this()
{
Delete(myArray);
free(myExternalData);
}
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store