Optional type - how to correctly reset a wrapped immutable T

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Mar 26 14:17:03 UTC 2018


On Monday, March 26, 2018 10:13:08 Simen Kjærås via Digitalmars-d-learn 
wrote:
> On Monday, 26 March 2018 at 09:46:57 UTC, Nicholas Wilson wrote:
> > Have a look at Rebindable:
> > https://dlang.org/phobos/std_typecons.html#rebindable
>
> Allow me to quote from aliak's post:
> > what I'm looking for is a Rebindable implementation that's for
> > value types
>
> As can be surmised from the above line, aliak has looked at
> Rebindable, and it doesn't work with value types.

It doesn't make sense for it to work with value types. Its entire purpose is
to be able to do the equivalent of const(T)* and immutable(T)* with classes.

If I correctly follow what the OP is trying to do, it's in violation of the
type system. You can't cast away const or immutable like that and mutate the
object. Honestly, what Rebindable does is pretty questionable as far as the
type system goes, but it does what it does by forcing pointer semantics on a
class reference, so the point is arguable. However, I think that the reality
of the matter is that Rebindable technically breaks the type system. It just
happens to do so in a way that always works, and there is no other way to do
what it does. But trying to do something like

struct Foo(T)
{
    const T _member;
}

where you cast away const and mutate the member is definitely in violation
of the type system and risks serious bugs depending on the optimizations
that the compiler chooses to employ - even more so if immutable is used.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list