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

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:

  1. Get the size of the memory block you need to use: __traits(classInstanceSize, ClassName).

  2. Allocate the memory, slicing it to get a sized array.

  3. Use std.conv.emplace to construct the class in place and cast the memory to the new type.

  4. Stop using the untyped memory block. Instead, use only the class reference.

  5. When you are finished, use destroy() to call the object's destructor, then free the memory.

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