Persistent list

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


On Sunday, 15 November 2015 at 08:59:52 UTC, Ola Fosheim Grøstad 
wrote:
> On Sunday, 15 November 2015 at 02:49:49 UTC, Jonathan M Davis 
> wrote:
>> the program's data. Certainly, any immutable objects created 
>> at runtime are only protected from mutation by the type system.
>
> That would be a bad assumption. It could be read only pages 
> with MMU protection. (files, shared memory etc)

Well, that's news to me, but my understanding of stuff that low 
level isn't very good. Regardless, my point is that there's no 
guarantee that anything other than the type system protects 
immutable variables against mutation. For instance, this code 
compiles and runs just fine.

     void main()
     {
         auto i = new immutable int(5);
         assert(*i == 5);
         auto j = cast(int*)i;
         *j = 42;
         assert(*i == 42);
     }

And there's this bug about how non-shared static constructors 
routinely mutate immutable variables:

https://issues.dlang.org/show_bug.cgi?id=4923

So, while there _are_ cases where mutating immutable memory will 
cause a segfault, there is no guarantee that casting and mutating 
an immutable variable will cause any obvious problems at all.

So, allowing const to be cast away for the purposes of mutation 
becomes _very_ dangerous, because it's very easy to screw up and 
mutate immutable objects, and given how differently the compiler 
treats immutable objects (e.g. they're implicitly shared and 
allow for eliding function calls when used in conjunction with 
pure) on top of the guarantees that the compiler gives about 
immutable objects never mutating, the consequences of mutating an 
object variable are far worse than they are with mutating a 
mutable object being via a const reference, even when doing that 
via a cast is currently undefined behavior.

So, if we choose to put a backdoor in const, it would be far 
better to do so with something like @mutable than to treat 
casting away const from an object and mutating it as defined 
behavior - though I think that we should be _very_ sure that 
we're willing to pay the cost of that backdoor before we make 
that choice.

- Jonathan M Davis


More information about the Digitalmars-d mailing list