Immutable member functions on mutable objects
Steven Schveighoffer
schveiguy at yahoo.com
Tue Dec 1 06:41:59 PST 2009
On Sun, 29 Nov 2009 07:23:07 -0500, Tomek Sowiñski <just at ask.me> wrote:
> I've got a problem calling an immutable getter on an "ordinary" object.
>
> struct A {
> float _pole;
> float pole() immutable {
> return _pole;
> }
> }
>
> void main() {
> A a;
> auto x = a.pole; // Ouch!
> }
>
> Error: function hello.A.pole () immutable is not callable using argument
> types ()
>
> There's no problem when pole is const. I assume the problem is the
> hidden "this" parameter (is it? the message is a bit confusing). Then
> again, A is implicitly convertible to immutable(A) so there shouldn't be
> a problem, no? Maybe a compiler bug?
>
> BTW, can someone explain what's exactly the difference between a const
> and immutable member function? The D page says only about the latter.
Don't forget that:
struct A {
float pole() immutable {...}
}
is essentially syntax sugar for:
struct A {}
float pole(immutable ref A this) {...}
It is a common misconception that const and immutable are *function*
decorators. They are actually decorators for the hidden 'this' reference.
When you look at it that way, it becomes hopefully much clearer how to
deal with const and immutable.
-Steve
More information about the Digitalmars-d-learn
mailing list