5 ms·
To ensure there are no side effects - at least to ensure that that object in question is not mutated. I think const refs are a little more useful than const po
by flatline 16y ago
To ensure there are no side effects - at least to ensure that that object in question is not mutated. I think const refs are a little more useful than const pointers for this.
- alextgordon 16y agoDo you find const actually catches bugs? I admittedly don't use C++ that frequently, but if I make my code const-correct it always seems to cause a lot of false positives, while seldom finding actual bugs.
- danieldk 16y agoI disagree, especially const-correct methods help avoiding mutation. The primary mistake IMO is that const can be cast away. Invariant should be invariant (like D).
- jpr 16y agoA lot of people seem to be horrified that you can cast constness away. Maybe they have more traumatic experiences than I do, but I believe that if something is possible to do (modifiying an object that is declared const), it should be possible in the language as well. That does not mean it should have well specified semantics or that it should be done without proper considerations.
- nickelplate 16y agoconst does not so much catch bugs as it prevents them. It is a way to specify a contract. If your code is const-correct, the next programmer using or maintaining your code can read a function or method signature and know immediately which parameters will not change, or whether the object will be modified. Effective C++ explains this very well, and I fell in love with const after reading its second edition almost 10 years ago.
- nostrademons 16y agoThat would be const type pointer. (HN apparently won't let me type more than one asterisk in the message without turning everything between them to italics.) const type pointer const is a const pointer to a const object, i.e. the pointer itself can't be mutated to point to a different object. I've never found a need for it. I usually don't care if the pointer itself is modified, particularly since such modifications are usually local and obvious.
- mansr 16y agoIt is useful for static (possibly global) data which if const can be placed in the read-only data section. For local variables or function parameters it is less useful.