const member functions

Janice Caron caron800 at googlemail.com
Wed Sep 12 23:19:19 PDT 2007


On another thread I pondered that the D2.0 syntax for const member
function was ambiguous. I've now come to believe it's also wrong.

What we're talking about is a function which would be declared like
this in C++ (with const at the end)

class C
{
    int f() const { /* ... */ }
}

in D2.0, apparently the syntax is:

class C
{
    invariant int f() { /* ... */ }
}

Here's my problem. f isn't invariant, by D's use of the word.

What makes f a member function is that it has access to a hidden
variable called "this". What makes f a /const/ member function is that
the type of "this" is const(C). NOT invariant(C). f gets a read-only
view of "this" - so, even by D2.0's keyword names, it should be
"const", not "invariant".

As followers of this know, I advocate rename invariant -> const, and
const -> readonly in any case, so under the renamed scheme, we would
call f a readonly function, because it has a readonly view of "this".

My suggestion for the syntax is to position the word "readonly"
immediately to the left of the function name. Thus:

class C
{
    readonly int f() { /* ... */ } /* this has type C; return type is
readonly(int) */
    int readonly f() { /* ... */ ) /* this has type readonly(C);
return type is int */
}

You could even use the bracket syntax if you wanted...

class C
{
    readonly(int)f() { /* ... */ } /* this has type C; return type is
readonly(int) */
    int readonly(f()) { /* ... */ ) /* this has type readonly(C);
return type is int */
}



More information about the Digitalmars-d mailing list