3 ms·
const is weird and I see no way of getting it right. Making const transitive in the way described in tha Dlang reference certainly sounds weird. It prevents tot
by jstimpfle 2y ago
const is weird and I see no way of getting it right. Making const transitive in the way described in tha Dlang reference certainly sounds weird. It prevents totally valid use cases. Why wouldn't I have a const pointer to a mutable thing?
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).
- pjmlp 2y agoHence why D has two approaches with similar semantics, const and immutable. 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.