Initialize class at given location

drug007 drug2004 at bk.ru
Fri Nov 28 18:42:44 UTC 2025


On 28.11.2025 21:14, tzsz wrote:
> Hello,
> I'd like to ask if there is any way of creating a class instance at a 
> location given by a pointer.
> In C++ this is usually done using new(pointer) MyClass(); and I saw a 
> post made by Walter Bright that suggested adding this to D. The code 
> from that post did not compile on my machine tho. And the post was a few 
> years old, so I don't know what the current state regarding this feature 
> is. I really tried finding something via Google but I was unsuccessful.
> 
> The reason for this is that I am looking for a way to use classes with 
> all their nice features but without the GC. Therefore I'd be doing all 
> the (de)allocations on my own. For this, I am currently using malloc and 
> free from core.stdc.
> 
> Kind regards

In C++ it is called placement new. In D you should emplace class:

```D
import core.lifetime : emplace;
import core.stdc.stdlib : malloc, free;
import std.stdio : writeln;

class MyClass
{
     int value;

     this(int v)
     {
         value = v;
         writeln("MyClass constructor called with value: ", value);
     }

     ~this()
     {
         writeln("MyClass destructor called for value: ", value);
     }
}

void main()
{
     // Allocate memory for MyClass
     void* rawMemory = malloc(__traits(classInstanceSize, MyClass));
     if (!rawMemory)
     {
         throw new Exception("Out of memory!");
     }

     // Cast the raw memory to the class type
     MyClass instancePtr = cast(MyClass)rawMemory;

     // Emplace the MyClass instance
     emplace!MyClass(instancePtr, 10);

     // Now you can use instancePtr as a regular class instance
     writeln("Value from emplaced instance: ", instancePtr.value);

     // Remember to manually call the destructor and free the memory for 
non-GC allocated objects
     destroy(instancePtr);
     free(rawMemory);
}
```


More information about the Digitalmars-d-learn mailing list