Why can't we define re-assignable const reference variable?
none
z at gg.com
Sat Feb 16 11:30:27 PST 2008
Why can't we define re-assignable const reference variable?
i.e. the variable can be re-bind, but it's allowed to change the object it
points to:
This is such a pain to port D 1.0 code to 2.0, e.g. I have some code in D 1.0
like this:
========================
B b1, b2;
b1 = new B();
b2 = new B();
B b;
b = b1;
b.MemberFunc(); // later change to const member function
b = b2;
b.anotherMemberFunc(); // later change to const member function
========================
When porting to D 2.0, some of the method of class B is changed to const
member function, and I want to make my intention clear, so I changed 'B b', to
be 'const B b'.
Now the trouble is, b can only be init-ed once, but cannot be re-assigned.
I know I can use pointer to achieve what I want:
========================
B b1, b2;
b1 = new B();
b2 = new B();
const(B)* b; // type change
b = &b1; // additional change
b.constMemberFunc();
b = &b2; // additional change
b.anotherConstMemberFunc();
========================
Then I have to change the code in multiple places; and the other problem is
that I will have to use pointers most of the time in my code.
So why can't we have both (just as in C++):
========================
const B b; // b cannot be re-bind, and the object cannot be modified
B const b; // b can be re-bind, but the object cannot be modified
========================
More information about the Digitalmars-d
mailing list