What guarantees does D 'const' provide, compared to C++?

Jesse Phillips Jessekphillips+D at gmail.com
Fri Aug 17 12:52:00 PDT 2012


> On Friday, 17 August 2012 at 02:14:22 UTC, Jonathan M Davis 
> wrote:
>> What I meant is that you know that nothing was altered through 
>> the reference that the getter returned. You don't have any 
>> such guarantee in C++.

Please reread what Jonathan has written above and look at my 
example below:

struct MyStruct
{
    static int* x;
    int* y;
    int z;
    this(int* z) { x = z; }
    auto getValue() const { ++*x; return this.y; }
}

void main() {
    auto s = MyStruct();
    s.y = &s.z;
    auto r = MyStruct(s.y);
    r.y = r.x;
    r.getValue();  // const, but returns 1
    r.getValue();  // const, but returns 2
    r.getValue();  // const, but returns 3

    auto m = r.getValue();
    *m = 5; // test.d(21): Error: *m is not mutable
}


More information about the Digitalmars-d mailing list