Article: Why Const Sucks

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Mar 5 14:09:08 UTC 2018


On Monday, March 05, 2018 13:53:21 SimonN via Digitalmars-d-announce wrote:
> On Monday, 5 March 2018 at 10:57:35 UTC, Jonathan M Davis wrote:
> > Here's something I wrote up on const:
> Excellent read! I enjoyed the history of proposed solutions.
>
> I've run into the trouble with annotated opEquals in classes
> several times. I believe an empty/nonexistant Object class is the
> correct solution, together with templates. If it breaks tricky
> opEquals-overriding usercode, then so be it. The const trouble is
> merely a symptom here, the real problem is Object.

Yes, the fact that those functions are on Object is a serious problem that
affects more than const, but part of the reason for explaining that
particular issue was to show how the use of const - or the lack thereof - on
a member function can have serious consequences for a class hierarchy. It's
by far the worst in the case of Object, because it affects _all_ classes in
D, but any time that someone designs a class in D that is intendend to then
have other classes derived from it, the same choices pop up; the
consequences are just then on a smaller scale.

> In structs, all const members feel alien, they preventing all
> copying. This seems far harder to solve.

Yeah. I don't know what we do about that. In general, I think that it makes
by far the most sense for value types to not be inherently const (even in
part), so I'm not all that worried about the problems that stem from making
a particular member variable const. But the fact that you then can't use a
postblit constructor with a const object - even if nothing in the object is
const unless the entire object is const - is definitely a problem.

IIRC, Walter's take on it was that it was bad design for objects to
deep-copy like that and that it was just better to use stuff like COW, in
which case, postblit constructors aren't generally needed. And as such, he's
a lot less worried about the problem than otherwise might be the case. I
agree that it's frequently problematic for copying to be expensive in that
manner, but it's also sometimes very useful. I expect that a good, solid DIP
on the subject would be accepted in spite of the fact that Walter isn't big
on postblit constructors, but first, someone has to come up with such a DIP,
and that's not even vaguely easy - especially if the answer doesn't involve
adding a copy constructor to the language (which I would guess would be
rejected due the extra complexity that it would add to the language, but I
don't know). Either way, right now, it's just one more thing on the list of
things that makes it difficult enough to use const in D that many of us use
it fairly minimally.

- Jonathan M Davis



More information about the Digitalmars-d-announce mailing list