Placement new and @trusted

Paul Backus snarwin at gmail.com
Thu Sep 11 04:19:02 UTC 2025


On Wednesday, 10 September 2025 at 14:31:27 UTC, IchorDev wrote:
> On Wednesday, 10 September 2025 at 13:13:34 UTC, Richard 
> (Rikki) Andrew Cattermole wrote:
>> Placement new is @system, but you wanted to use it in an @safe 
>> function iff the constructor to be called is @safe as well.
>
> Pretty much.
>
>> The reason placement new is @system is because of double-init. 
>> It can't be a safe operation.
>
> What?! Like, it assigns to the memory twice? What's the point 
> of this feature, then? I thought this could essentially replace 
> `emplace` for constructing types into uninitialised memory, but 
> instead it's just a booby-trap that stops people from making 
> their code `@safe`?

The problem is not really with placement new, it's with 
constructors. Constructors are allowed to mutate immutable 
objects (under the assumption that they are initializing a 
newly-created object). If you call a constructor twice on the 
same immutable object, which is possible with placement new, it 
can result in undefined behavior.

In fact, it is also possible to trigger UB this way by simply 
calling the constructor manually: 
https://github.com/dlang/dmd/issues/20248


More information about the Digitalmars-d-learn mailing list