C++ and const

Why does C++ have the const keyword? How often has it saved you from bugs? How many times have you seen “passing T to func ignores const” and it’s been because func really modifies T, and not just that you forgot to put const on the function? How many times have you seen that warning because you just forgot to mark something const that should have been? So why is const there other than an bit of enforced documentation? If it’s just enforced documentation how about some other semi-enforced documentation that might be useful? nonnull would be a great one especially for return types. In/Out/InOut are commonly used bits of information for documentation generators, so they must be important. What about “pure” on a function (has no side effects, so it can be hoisted out of loops, etc?) How about “owned” or “owned” on pointers? maybe “heap” for pointers that will be later free(3)’d and therefore must be on the heap? Why was const important enough to get the reserved word status, and why did nothing else get it? Why aren’t there programs out there that look at your code and say “Hmm, you should put a const here, and here, and here, and here”, in fact, why isn’t the compiler just figuring out if things should be const by itself? In fact why doesn’t the compiler look at the symbols that are defined in a .cc file and generate a .h of all the exported symbols anyway with annotations that the compiler might find useful (pure, const, non null, heap, etc)?

Sigh, I might be bitter and twisted about being forced to stick const on everything for no better reason than it makes my code look pretty, but why oh why is it there?

Comments are closed.