Article: Why Const Sucks

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Mar 5 18:32:51 UTC 2018


On Mon, Mar 05, 2018 at 11:04:49AM -0700, Jonathan M Davis via Digitalmars-d-announce wrote:
> On Monday, March 05, 2018 09:38:52 H. S. Teoh via Digitalmars-d-announce 
> wrote:
> > Eventually, I discovered that the underlying problem was that
> > Result, as defined above, was a struct with a const member, and
> > therefore it was illegal to assign it to a variable of the same type
> > outside of initialization (since doing do meant you were overwriting
> > a const field with something else, which violates the constness of
> > the field).  This broke the by-value assumption inherent in much of
> > Phobos code, so the resulting range ended being unusable with most
> > Phobos algorithms.  Which defeated the whole purpose in the first
> > place.
> 
> Honestly, I've come to the conclusion that structs should never have
> const or immutable members. It just causes too many problems. Treating
> them as read-only from the outside by having them be private and have
> member functions be const is fine (assuming that const works in that
> case), and having them work when the entire object gets marked as
> const is great (assuming that const works in that case), but I think
> that it's pretty much always a mistake to make individual member
> variables of a struct const or immutable.
[...]

Yeah, but in this case, since `this` is const, there's simply no way to
get around the fact that there must be `const` somewhere in the Result
struct.  The D compiler will not accept a mutable member referencing
`this` that has a const access method, since that in theory breaks the
const guarantee.  I suppose replacing `const(Container)` with tail-const
references to Container's innards would fix the problem, but it would
uglify the code too much and would be far too much effort just to be
able to say "we support const", that it's simply not worth it.

Also, structs with const/immutable members are a rare case allowed by
the language but almost never tested for in Phobos, so you can pretty
much expect random things to break left, right, and center if you ever
attempt to use such a struct with Phobos functions.  In fact, I vaguely
remember that even the compiler may have bugs / strange behaviours if
you try to use such structs in non-trivial ways.


T

-- 
Never step over a puddle, always step around it. Chances are that whatever made it is still dripping.


More information about the Digitalmars-d-announce mailing list