union mutability
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Aug 25 09:40:07 PDT 2016
On Thursday, August 25, 2016 15:22:23 Jack Applegame via Digitalmars-d-learn
wrote:
> Code:
>
> union A {
> immutable int f;
> }
>
> union B {
> immutable int f;
> int e;
> }
>
> void main() {
> A a = A(1);
> //a = A(2); // a.f is immutable, fails to compile as expected
>
> B b = B(1);
> b = B(2); // compiles!!!
> }
>
> It turns out that if the union contains at least one mutable
> member, then the entire union is considered to be mutable.
> It's logical, but does it meet the specs? I couldn't find
> description of this behavior.
Well, Rebindable depends on it (though Rebindable is in a legal grey area at
best and technically in violation of the rules at worst). It's basically the
same as when you cast away const or immutable - it's fine as long as you
don't mutate the variable and thus break the guarantees that compiler has
for const or immutable objects. But I don't know how you can really do
anything with it without violating immutable. Certainly, in any case other
than what Rebindable is up to, I wouldn't do it, and even then, I suspect
that Rebindable is in a situation where it's technically violating the
compiler's guarantees but does so in a way that will never actually result
in problems in practice.
But yes, this behavior is known, albeit questionable.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list