Placement new and @trusted

Nick Treleaven nick at geany.org
Fri Sep 12 10:20:45 UTC 2025


On Thursday, 11 September 2025 at 08:06:17 UTC, IchorDev wrote:
> But that's the thing: all I want is to construct objects into 
> *freshly-allocated*, *uninitialised memory*; so my desired 
> use-case has a safe interface and can therefore be marked 
> `@trusted`. However the constructor is a wildcard, so I want to 
> leave that part to attribute inference.
> Do you think it'd be worth submitting an enhancement issue to 
> add something simple like this?
> ```d
> new @trusted (buffer) S(500); //we trust that the buffer is 
> safe to use, but not S's constructor.
> ```

No, for 2 reasons:

1. `@trusted` is a function attribute that says the function has 
a safe interface. Placement new does not have a safe interface, 
above it depends on how `buffer` is used outside of it and what 
`S` is. (Yes people often resort to using a trusted function 
literal without a safe interface, but it's still wrong, and the 
language shouldn't endorse that).

2. There are various other expressions in the language where 
you'd need something similar. Phobos uses introspection instead 
to detect whether to trust an expression or not.

> The weird placement new syntax means that this looks a bit 
> goofy, but it's better than the feature being essentially 
> dead-on-arrival for the *one thing* I'd ever want it for.

It's no different than some other unsafe expressions that Phobos 
sometimes needs to trust.


More information about the Digitalmars-d-learn mailing list