(yes yes, I know, that would break syntax... but please come up with something to discourage mutability)
(yes yes, I know, that would break syntax... but please come up with something to discourage mutability)
Yeah I know there's ways around it, but then the author known what they told the other party to expect.
The real problem is that it's not defined what is an object, and where, in a web of memory-objects pointing to each other, a conceptual object begins and ends. It's arbitrary. Also, what is const from one standpoint is not const from another. It's fluid. Type systems generally don't play well with that. The weirdness of the original `strstr()` C API showcases that problem well.
The only thing that makes some sense here is to keep it simple -- any struct-like thing is an individual object. Embedded objects of course inherit const-ness, but pointed-to objects do not.
I think the C++ model is also somewhat right -- any class can define individually through which indirections const-ness follows through. But the C++ way causes lots and lots of boilerplate.
In any case, my solution is to use const very sparingly, it can hardly be gotten right in practice beyond basic use. Being more rigid of const may have prevents 2-3 bugs in my life, but cost sooo much more time and required many rewrites to make it fit somehow.
I use const mostly for
- static const data
- some string-slice datatypes (these are often initialized from static const data like string literals).
- read-only function parameters passed by reference (Foo const *thing).
And also allows to alias non const references to the same data.
Thus the data can be modified by a mutable reference, owned by a specific part of the code, while everyone else only gets to see the const chain.