Manually managing class memory
The new operator in D uses the garbage collector, but it isn't the only option. When interfacing with other languages' code or working in a constrained-resource environment (possibly including tight loops on fast PCs!), it is useful to avoid the new operator. Let's see how.
How to do it…
In order to manage class memory manually, perform the following steps:
Get the size of the memory block you need to use:
__traits(classInstanceSize, ClassName)
.Allocate the memory, slicing it to get a sized array.
Use
std.conv.emplace
to construct the class in place and cast the memory to the new type.Stop using the untyped memory block. Instead, use only the class reference.
When you are finished, use
destroy()
to call the object's destructor, then free the memory.Be careful not to store the reference where it might be used after the memory is freed. You may want to create a reference counting
struct
to help manage the memory.
How it works…
The __traits
function retrieves information...