www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - const system in OO code

reply Alex Burton <alexibu mac.com> writes:
I am struggling to understand this new const system. I've read the
documentation and article about const, but I don't have windows, so I've been
unable to test D 2.0.
It looks like great strides have been made to improve compilation which is
great.
I am unsure that it is any better than C++ in OO style code.
In order for const to work, the compiler needs to be able to tell whether
objects are part of a class or just other objects referenced by a class.
In C++ if an object is part of a class you can go class B { A a; }; or if a
pointer is required because A is an interface etc, class B { aggregate_ptr<A>
a; }; where aggregate_ptr is a smart pointer with two overloaded -> operators
one const returning const and one non const returning non const.
If a method of B is marked const, the compiler can tell if *a is modified,
therefore by virtue of a being part of B, that B is modified and the code is
invalid.
Alternatively you could go class B { A * a; }; and modify *a as there is no
part of relationship expressed.

Moving to D, there is only class B { A a; } where a is a pointer, the compiler
and programmer now have no idea whether or not a is part of B.

So there are two options, declare that a cannot be modified in an invariant
method of B,
or declare that a can be modified in an invariant method of B.
Both of these options are unsatisfactory IMO.
Please help if I am missing something.

Some example code below :

class A
{
    int x;
};

class B
{
    this(A a_in)
    {
        a = a_in;
    }
    A a;                    //nothing to say here whether a is logically part
of B or is some other object we have a reference to.
    int x;
    invariant foo()
    {
        a.x++;            //is this an error because invariant is 'transitive' ?
        x++;               //An error because invariant method cant modify class
    }
};


void bar(const B b)
{
    b.foo();     //this is an error - const B b means we cannot call invariant
methods.
    b.x++;      //this is an error - const B b means we cannot modify b.
    b.a.x++;   //is this an error ?
}

int main()
{
    B b = new B(new A);
    bar(b);
}
Jun 27 2007
parent BCS <BCS pathlink.com> writes:
Alex Burton wrote:
 ...I don't have windows, so I've been unable to test D 2.0.
DMD will also run on linux (OTOH If you are on mac or something else... can't help you)
Jun 27 2007