Const by Default
Don Clugston
dac at nospam.com.au
Mon Jun 25 03:31:51 PDT 2007
David B. Held wrote:
> I think an interesting point was brought up in the earlier CbD thread,
> which is specifically the issue of c'tors, and generally, the issue of
> passing mutable references. So consider:
>
> class MyObj
> {
> this(MyClass a, MyClass b)
> {
> a_ = a;
> b_ = b;
> }
> private:
> MyClass a_;
> MyClass b_;
> }
>
> With CbD, this code is incorrect. Would you like to explain to a novice
> programmer why?
Because you're retaining a writable copy of a and b, so the class could modify
them at any future time. You probably didn't intend to do that.
You need to make a_ and b_ const.
But if you truly want to be able to modify them later, you obviously need them
to be inout.
I don't see how this case is any different to a member function
void func(MyClass a, int b) {
a.dosomething(); // of course this is incorrect,
// you need to get non-const access to a.
}
I don't see any problem here.
More information about the Digitalmars-d
mailing list