mutable, const, immutable guidelines

qznc qznc at web.de
Thu Oct 17 00:08:16 PDT 2013


On Wednesday, 16 October 2013 at 20:33:23 UTC, H. S. Teoh wrote:
> I'm of the view that code should only require the minimum of 
> assumptions
> it needs to actually work. If your code can work with mutable 
> types,
> then let it take a mutable (unqualified) type. If your code 
> works
> without modifying input data, then let it take const. Only if 
> your code
> absolutely will not work correctly unless the data is 
> guaranteed to
> never change, ever, by anyone, should it take immutable.

What about functions, which are not thread-safe?

auto percentageDistribution(const int[] percentages) {
   [...]
   assert (sum == 100);
   [...]
}

Not a realistic example, but it should do. This function checks 
that the sum of all percentages equals 100, but a concurrent 
modification might break this. You could require an immutable 
array to avoid that. Alternatively, the absence of "shared" could 
be considered enough to express this.


More information about the Digitalmars-d-learn mailing list