const and immutable member variables in classes

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 2 21:08:07 PST 2016


On Tuesday, February 02, 2016 19:32:39 Ali Çehreli via Digitalmars-d-learn wrote:
> On 02/02/2016 07:05 PM, Jonathan M Davis via Digitalmars-d-learn wrote:
>  > I usually tell folks not to do it because of
>  > all of the problems it causes.
>
> That's been my guideline: "const and immutable members should be
> avoided." Now I'm tempted to add this: "only in structs."

IIRC, I've pretty much always been telling folks specifically to not have
structs with const or immutable members and haven't generally said anything
about classes.

But I really don't see any reason to avoid it in classes at this point.
Maybe if a serialization mechanism were involved, it would matter, but the
class would probably have to be designed to support that given that there is
no equivalent to the assignment operator for the class objects themselves
(just their references). Ultimately, it's the ability to overwrite the state
of the object that's the problem, and that simply isn't an issue with class
objects under normal circumstances.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list