Initializing an Immutable Field with Magic: The "Fake Placement New" Technique

FeepingCreature feepingcreature at gmail.com
Fri Jul 26 16:24:26 UTC 2019


On Friday, 26 July 2019 at 15:55:14 UTC, ag0aep6g wrote:
> On 26.07.19 17:35, FeepingCreature wrote:
>> On Friday, 26 July 2019 at 15:32:49 UTC, ag0aep6g wrote:
>>> As shown initially, if you don't mind relying on UB, you can 
>>> also just cast.
>> 
>> As *immediately answered*, no you *can't*. You can't write a 
>> generic function that assigns a new value to a pointer with 
>> cast, because the immutable may be on a field, and in any case 
>> the value may have assignment disabled.
> struct S { immutable int i; @disable void opAssign(S); }
> void f(S* ptr)
> {
>     * cast(ubyte[S.sizeof]*) ptr = cast(ubyte[S.sizeof]) S(5);
> }

Ah, good point. I believe this is approximately what moveEmplace 
does anyways. (Except with a memcpy.)


More information about the Digitalmars-d mailing list