Inability to dup/~ for const arrays of class objects

monarch_dodra monarchdodra at gmail.com
Wed May 29 02:40:07 PDT 2013


On Wednesday, 29 May 2013 at 01:05:14 UTC, Peter Williams wrote:
> I'm implementing sets and the concept is sets of objects not 
> sets of the values in the objects.  I want to be able to 
> initialize sets using arrays and I'm promising that I won't 
> change the array or its contents.
>  I'm also trying to promise that I won't (inside the set 
> implementation) make any changes to individual objects.  But 
> I'm not promising that they won't be changed by other code that 
> has access to them.  The invariant (I wrote) for the sets 
> implies that any changes made by that code can't change the 
> sort order of the objects.
>
> Peter

The problem is that you are missing a FUNDAMENTAL difference 
between C++ and D. C++'s const merely says: "Though shalt not 
modify this value", whereas D's means "This object's value WILL 
remain constant, until the end of time, and under no circumstance 
can it ever be modified. Oh. And so will everything it 
references".

The fact that *you* are promising to not change it is irrelevant 
to the concept of D's const. D only knows 2 states: objects that 
mutate, and objects that don't mutate.

Ditto about invariants. Contrary to C++, there is no concept of 
"observable constness" (eg invariants).

The reasoning behind this is that in D, const is actually the 
"base attribute" between the "muttable" and the "immutable" 
objects. immutable allows sharing things accross threads, and 
allows more aggressive optimizations than is possible with const 
"the compiler *knows* the object will not be changed by an 
outside force". At this point, const exists only to be able to 
operate on objects that may or may not be immutable.

For example, imagine you have a const array of pointers, and you

--------
Of course, this has its limits, and that's where casting comes 
into play. You must keep in mind these two caveats:
*Never ever ever modify something that is const.
*Once you've casted something to const, make sure that NOTHING 
will modify the object via a non-const handle.

But the "const" you are trying to promise is not what D's const 
was designed for.


More information about the Digitalmars-d mailing list