Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing immutable members inside the constructor

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?

like image 866
fredoverflow Avatar asked Nov 18 '25 20:11

fredoverflow


2 Answers

Probably because the reference to increment isn't scope, so it has the potential to be escaped past the scope of the constructor, which would break the immutability of member, and the compiler can't verify that it's fine.

(It might be that scope won't work either, but it should. If implemented properly, I think scope would 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.

like image 125
user541686 Avatar answered Nov 21 '25 10:11

user541686


What if increment was this?

int* p;
void increment(ref int i)
{
    p = &i;
}

Uh oh, you've created a mutable reference to immutable data, breaking the type system.

like image 40
Peter Alexander Avatar answered Nov 21 '25 08:11

Peter Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!