logical const is a subset of transitive const
Janice Caron
caron800 at googlemail.com
Fri Sep 14 13:31:31 PDT 2007
On 9/14/07, Bill Baxter <dnewsgroup at billbaxter.com> wrote:
> Was the point of const
Dunno about the "point".
A const /function/ (as opposed to a const /object/) is a member
function of some class T which can see a hidden variable called "this"
of type const(T).
...or put another way, it can't modify any member variables of the class.
There's no such thing as a const function which is not a member
function. That would make no sense.
A non-const member function can also see a variable called "this", but
this time it's of type T, not const(T).
So yes, a const function can still read and write global variables.
For that matter, it can even legitimately modify it's own class member
variables - but only through another pointer! For example:
class A
{
int x;
const void f(A a)
{
a.x = 3;
}
}
A a = new A();
a.f(a);
I guess the "point" of a const function is exactly the same as the
"point" of a static or global function which takes a const parameter.
Same difference. In either case, there's an object which is physically
const. The compiler can make presumably make some assumptions and/or
optimisations concerning that variable.
What I /don't/ understand is why D lets you declare a member function
(as opposed to an object) as being invariant. To my brain, that ought
to mean the function sees "this" as having the type invariant(T) - but
that's clearly an invalid assumption, because "this" /can/ be
modified. You have a read-only view, that's all.
"Pure" on the other hand, only makes sense for functions. So far as I
know, there's no such thing as a pure object.
More information about the Digitalmars-d
mailing list