Constructing Variables at Specific Memory Locations

You will learn how to construct struct and class objects at specific memory locations in this lesson.

The new expression achieves three tasks:

  1. It allocates memory large enough for the object. The newly allocated memory area is considered to be raw, not associated with any type or any object.

  2. It copies the .init value of that type on that memory area and executes the constructor of the object in that area. Only after this step is the object placed on that memory area.

  3. It configures the memory block so it has all the necessary flags and infrastructure to properly destroy the object when freed.

We have already discussed how the first of these tasks can explicitly be achieved by memory allocation functions like GC.calloc. Being a system language, D allows the programmer to manage the second step as well.

Variables can be constructed at specific locations with std.conv.emplace.

Constructing a struct object at a specific location

emplace() takes the address of a memory location as its first parameter and constructs an object at that location. If provided, it uses the remaining parameters as the object’s constructor arguments:

import std.conv; 
// ...
    emplace(address, /* ... constructor arguments ... */);

It is not necessary to specify the type of the object explicitly when constructing a struct object because emplace() deduces the type of the object from the type of the pointer. For example, since the type of the following pointer is Student*, emplace() constructs a Student object at that address:

    Student * objectAddr = nextAlignedAddress(candidateAddr);
// ...
    emplace(objectAddr, name, id);

The following program allocates a memory area large enough for three objects and constructs them one by one at aligned addresses inside that memory area:

Get hands-on with 1200+ tech skills courses.