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:

  1. Write a struct that performs cleanup operations in the destructor.
  2. 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 in the instance) is safe. You may use a class destructor to free C resources when the garbage collector runs, for example.

You may manually call destroy(obj) to destroy any object immediately. Together with a scope(exit) guard, you can deterministically call a class destructor. The destroy function does not free memory, it merely finalizes the object.

In modern D, there is no delete operator. D used to have a delete operator, like C++; however, it was deprecated because it limits the garbage collector implementation and is not memory safe. If you want to manually release memory, you should also manually allocate it.

Given these limitations of class destructors, implementing the RAII idiom in D is typically done with structs. Struct destructors always run immediately when the struct ceases to exist and have full access to all child memory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.71.106