Initialize class at given location

Steven Schveighoffer schveiguy at gmail.com
Sat Nov 29 01:59:16 UTC 2025


On Friday, 28 November 2025 at 18:14:15 UTC, 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.

This is a newly added improvement, and only in the most recent 
compiler

```d
struct S
{
     int x;
}
void foo()
{
     ubyte[S.sizeof] arr;
     auto s = new(arr) S(1);
     assert(arr == [1, 0, 0, 0]);
}
```

builds with 2.111.0. But it doesn't work (assert fails). 
Apparently there was a bug here.

dmd-nightly does work.

See the [changelog 
entry](https://dlang.org/changelog/2.111.0.html#dmd.placementNew).

-Steve


More information about the Digitalmars-d-learn mailing list