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

ag0aep6g anonymous at example.com
Fri Jul 26 15:55:14 UTC 2019


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);
}


More information about the Digitalmars-d mailing list