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.

Classes don't have the same problem, because they're on the heap and don't
get copied, but with structs being on the stack and very much being designed
with copying in mind, members that can't be copied becomes a definite
problem.

Tail-const and tail-immutable would work fine with member variables in
structs, but that basically means that the data for those members has to be
on the heap, which isn't always a reasonable option.

> So yeah, while D's const provides actual guarantees unlike C++'s
> laughable const-by-documentation, that also limits its scope so much
> that in practice, it's rarely ever used outside of built-in types like
> string. Which also limits the usefulness of its guarantees so much that
> it's questionable whether it's actually worth the effort.

Exactly.

- Jonathan M Davis

Reply via email to