Immutable member functions on mutable objects
Tomek Sowiñski
just at ask.me
Sun Nov 29 10:15:19 PST 2009
Simen kjaeraas Wrote:
> On Sun, 29 Nov 2009 13:23:07 +0100, 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.
> >
> > Tomek
>
> A is not implicitly castable to immutable(A), only to const(A).
I think it is. This compiles:
immutable a = A(3.4);
But only because it's copied.
> const member functions can be called on any A, unmarked ones only
> on A, and immutable ones only on immutable(A).
Concise and enlightening. Thanks.
> Basically, immutable is there to give future optimization options,
> and immutable objects are not interchangable with mutable objects.
> const is the "missing link", allowing one to pass both mutable and
> immutable to a function taking const parameters.
>
> An explanation often given on these newsgroups is that const is a
> read-only view of the data, whereas immutable is a promise that
> the data will never change.
I more or less understand the const system on variables. It was the function annotations that got me. Before your answer my thinking was: a const function promises to leave "this" (and anything accessible through it?) alone. What more promise could marking a function immutable give?
BTW, the future optimization options are about removing locks or something more?
Tomek
More information about the Digitalmars-d-learn
mailing list