Using RAII and handling the limitations of class destructors
D can use the Resource Acquisition Is Initialization (RAII) idiom from C++. This is when resources are acquired when the variable is initialized and automatically released when the variable goes out of scope.
How to do it…
Perform the following steps:
Write a struct that performs cleanup operations in the destructor.
If you use a class destructor, be certain that you don't access any memory external to the object or manually manage the class memory.
How it works…
Structs with destructors are called deterministically, just like in C++. Class destructors are less reliable. D's garbage collector may be implemented with a variety of strategies, so the language semantics are flexible. The garbage collector is free to release memory referenced by the object's pending finalization. This means accessing child objects or arrays in a class destructor risks a crash. Accessing manually managed objects or shallow class references (value types embedded...