Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...