Persistent list

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sun Nov 15 10:00:10 PST 2015


On Sunday, 15 November 2015 at 17:38:10 UTC, Andrei Alexandrescu 
wrote:
> On 11/15/2015 10:09 AM, Jonathan M Davis wrote:
>> const in D guarantees that the object will not be mutated via 
>> that
>> reference regardless of what that reference refers to.
>
> We need to change that if we want things like composable 
> containers that work with const. And I think it's a good thing 
> to want. -- Andrei

Basically, we have to decide between having physical const with 
the guarantees that it provides (but losing out on being able to 
use const in a _lot_ of places) and having a transitive version 
of C++'s const (which means losing out on the solid compiler 
guarantees).

The guarantees that we get with physical const are really nice, 
but yes, they do come at the cost of not being able to use const 
in a _lot_ cases. So, it could very well be that we'd better off 
losing physical const. And one thing to consider is that there 
are plenty of folks who mistakenly think that it's okay to cast 
away const and mutate an object as long as the object isn't 
actually immutable, so there's plenty of code out there that 
already does that. It almost certainly works, because the 
optimizations that the compiler can make based on const alone are 
extremely limited, but it _is_ undefined behavior, and if it's 
that easy for folks to misunderstand and end up relying on UB, 
maybe we should just change it so that it's defined behavior.

I don't know. I like physical const as it is, but it so often 
seems too limiting to actually be useful, which ultimately 
probably means that we need to change it (in order to take into 
account human behavior if nothing else, since const is clearly 
being misunderstood and misused as-is).

That being said, even if we make it defined behavior to mutate a 
mutable object via a const reference via casting, I think that 
having @mutable like you suggested would still be a good idea, 
because it would cover one of the primary use cases where casting 
would be required and eliminate the need for that cast and 
disallowing immutable where it would be violated if it were used, 
making such idioms safer.

The other major use case that I can think of would be lazy 
initialization, and @mutable doesn't seem like the appropriate 
thing for that, but maybe we can add something else for it if 
we're already loosening the restrictions/guarantees on const (I 
think that someone just created a DIP for that too, though I 
haven't looked at it yet).

Regardless, we need to be very careful about what we do with 
casts involving const because of how easy it is to screw up and 
mutate an immutable objects in the process.

- Jonathan M Davis


More information about the Digitalmars-d mailing list