void increment(ref int i)
{
++i;
}
class Class
{
immutable int member;
this(int parameter)
{
member = parameter;
++member; // okay
increment(member); // compile-time error
}
}
Why is ++member okay, but increment(member) isn’t? Shouldn’t both behave the same way?
Probably because the reference to
incrementisn’tscope, so it has the potential to be escaped past the scope of the constructor, which would break the immutability ofmember, and the compiler can’t verify that it’s fine.(It might be that
scopewon’t work either, but it should. If implemented properly, I thinkscopewould fix a lot of bugs like these, as well as providing for interesting optimizations. If it doesn’t, I’d say it’s a bug.)I’ve pointed out semi-similar bugs before, but with delegates.
Const/immutable do have such problems in D.