Dicebot on leaving D: It is anarchy driven development in all its glory.

tide tide at tide.tide
Tue Aug 28 19:39:20 UTC 2018


On Tuesday, 28 August 2018 at 17:02:46 UTC, H. S. Teoh wrote:
> On Tue, Aug 28, 2018 at 08:18:57AM +0000, Eugene Wissner via 
> Digitalmars-d wrote: [...]
>> There are still valid use cases where const should be 
>> "broken". One of them is mutex (another one caching). I have 
>> very little experiance in multi-threaded programming, but what 
>> do you think about "mutable" members, despite the object is 
>> const?
>
> The problem with compromising const is that it would invalidate 
> any guarantees const may have provided.  Const in D is not the 
> same as const in languages like C++; const in D means 
> *physical* const, as in, the data might reside in ROM where 
> it's physically impossible to modify. Allowing the user to 
> bypass this means UB if the data exists in ROM.

I feel that such a narrow use case, wouldn't you just use 
something like immutable instead.

> Plus, the whole point of const in D is that it is 
> machine-verifiable, i.e., the compiler checks that the code 
> does not break const in any way and therefore you are 
> guaranteed (barring compiler bugs) that the data does not 
> change.  If const were not machine-verifiable, it would be 
> nothing more than programming by convention, since it would 
> guarantee nothing.  Allowing const to be "broken" somewhere 
> would mean it's no longer machine-verifiable (you need a human 
> to verify whether the semantics are still correct).

This is still not true, it is not machine verifiable as it is. It 
can be bypassed quite easily, as a const object can be assigned 
from an non-const one. There's no way to offer that guarantee.

import std.format : format;

struct Type
{
     int value;
}

void test(const ref Type type, int* ptr)
{
     int first = type.value;

     *ptr = first + 1;

     assert(type.value == first, format!"%d != %d"(type.value, 
first));
}

void main()
{
     Type type = Type(10);
     test(type, &type.value);
}


More information about the Digitalmars-d mailing list