mutable, const, immutable guidelines

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Oct 17 20:32:35 PDT 2013


On Thu, Oct 17, 2013 at 09:08:16AM +0200, qznc wrote:
> 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.

In D, variables are thread-local by default, and only shared if
explicitly stated so. If this function took shared(const(int)[]), or you
pass it something that's __gshared, then you might have a point. But in
normal D code I'd recommend against doing that.

Currently, D has some issues in the area of shared, requiring a cast to
strip shared from the type. So basically the onus is on the caller to
ensure that when shared is stripped from the type it's actually safe
from concurrent modification. In which case the above code should be OK
as-is.


T

-- 
Guns don't kill people. Bullets do.


More information about the Digitalmars-d-learn mailing list