How to return a const handle (view) to a mutable member of an agregate

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 13 16:57:43 PDT 2016


On Sunday, 13 March 2016 at 22:34:54 UTC, Chris Wright wrote:
> In theory, it can't be modified. As a practical matter, unions 
> and casts will allow people to modify it.

Saying that it *can't* be modified is slightly besides the point, 
yeah. It *must* not be modified. Casting away const and then 
mutating will probably just work as expected much of the time. 
But it's not allowed by the language. One must not do it.

I think it's important not to give the impression that it's ok in 
practice to cast away const and then mutate.

By the way, I don't think unions are in the exact same boat as 
casts here. With a union of const and mutable types, I'd say it's 
perfectly fine to mutate the data through the mutable one. Such a 
union is similar to having const and mutable pointers to the same 
data. Unions of immutable and mutable types are weird, though.

> Decorating your code with @safe is intended to prevent these 
> holes (and other types of unsafe code).

But even in non- at safe code, the compiler doesn't just accept 
mutating through a const reference. It requires a cast, which is 
an explicit signal to just do what the programmer says. There's a 
similar signal for ignoring @safe: @trusted.


More information about the Digitalmars-d-learn mailing list