Initializing an Immutable Field with Magic: The "Fake Placement New" Technique
FeepingCreature
feepingcreature at gmail.com
Fri Jul 26 14:47:10 UTC 2019
On Friday, 26 July 2019 at 14:19:11 UTC, ag0aep6g wrote:
> The interesting part is whether you're relying on undefined
> behavior with your union/__ctor stuff. If yes, then your code
> is just invalid. If no, then you can break the immutability
> assumption in a seemingly valid way. That would be interesting,
> but I'm not convinced that your code is valid.
>
> The pain points:
> 1) The spec doesn't say clearly when union fields are
> considered initialized.
> 2) DMD allows @safe access of (uninitialized) immutable union
> fields.
> 3) __ctor can be called on an existing instance in @safe code.
> That's clearly a bug.
I think you are just seriously overestimating the D spec.
Note that undefined behavior is a term of art arising from C/C++,
referring to behavior explicitly called out as open to the
compiler implementation. __ctor is not undefined behavior; I'd
call it "unofficial behavior". The spec doesn't mention it.
It so happens that defining a constructor, which validly
initializes an immutable field, also defines a magical added
function __ctor, on which the spec says nothing, but which
happens to have the same effect as the constructor. Such a
function could not be written normally, but it appears anyways.
In any case, this is frontend business, and there is only one
frontend and unlikely to ever be another, especially an
incompatible one. So as unofficial business goes, it's probably
pretty reliable. It might be changed, but if so, it'll probably
be marked deprecated; even if not, some other technique will
appear in its place. (emplaceRef still has to be implemented
*somehow*.)
More information about the Digitalmars-d
mailing list