getting rid of immutable (or const)

Ali Çehreli acehreli at yahoo.com
Thu Sep 5 15:48:40 UTC 2019


On 09/05/2019 07:31 AM, berni wrote:
 > On Thursday, 5 September 2019 at 13:27:55 UTC, drug wrote:
 >> [...]when you put it into an AA you modify old value
 >
 > Why?!? :-o When putting it into an AA it will be copied to a different
 > place in memory,

That's the misunderstanding: The existing object is assigned over. The 
address is the same:

void main() {
   int[int] aa;
   aa[1] = 1;
   const oldPointer = (1 in aa);
   aa[1] = 11;
   assert(oldPointer is (1 in aa));  // Passes
}

 > but the value is still the same, it's not modified.

const or immutable members make structs unassignable.

Whether the members of a type are const or immutable should not be 
dictated by where the objects of that type will be used. If it makes 
sense otherwise, sure...

If you are worried about existing elements being modified, you can 
provide a different container that wraps an AA, but provides an opIndex 
that returns 'ref const(T)'. That would solve the immutability of the 
elements in the container.

Ali



More information about the Digitalmars-d-learn mailing list