Hacker News new | ask | show | jobs
by magicalhippo 1120 days ago
Perhaps it depends on the code-base. I worked on a medium complexity C++ project (~300kLOC) but which used multi-threading quite heavily with shared data structures, and there was only a couple of instances where I felt it got in the way.

In the vast majority of cases it reduced my cognitive load significantly because I could just look at the method declaration and see that my code would be fine.

1 comments

Yes, as always it all depends on the context and how features are used. Maybe I was just bitten too often in situation where const is particular gnarly to use. I know for sure that in many cases, such as when calling small helper functions for copying a shallow array and such, one can easily pass pointer as pointers-to-const.

However, IME there is a big problem with const for more database-y, more stationary in-memory data. This is the kind of data that is almost always going to be mutated by at least some part of the code at some point in time. There is a fundamental problem of communication between mutating code and non-mutating code (the "strstr()" function, that has to apply a const-cast hack internally to implement its interface, is a trivial example here).

As said there are certainly situations where such "communication" isn't needed, but I'm anxious about precluding the possibility in the name of const-correctness.

I feel that instead of const (or whatever static formalized description of what a function is doing), good naming is most helpful to intuit broadly what that one function was doing again.

In C at least, I've ended up leaving const almost exclusively for the cases where the data is truly const - i.e. in the .ro section of the binary, and I know for sure it won't ever have to be modified, and basically I have to apply the const qualifier lest it puts the data in the wrong section / it needs an awful cast to remove the const. The majority of those are string literals typed as "const char *".