FAQ 14.05 Is const correctness tedious?It is no more tedious than declaring the type of a variable. In C++, const correctness is simply another form of type information. In theory, expressing any type information is unnecessary, given enough programmer discipline and testing. In practice, developers often leave a lot of interesting information about their code in their heads where it cannot be exploited or verified by the compiler. For instance, when programmers write a function such as the following print() function, they know implicitly that they are passing by reference merely to avoid the overhead of passing by value; there is no intention of changing the string during the print() operation. #include <string> using namespace std; void print(string& s); // Does not change s <-- 1
If this information is documented only by comments in the code or in a separate manual, it is easy for these comments to become inconsistent with the code; the compiler can't read comments or manuals. The most cost-effective way to document this information is with the five-letter word const: void print(const string& s); <-- 1
This form of documentation is succinct, in one place, and can be verified and exploited by the compiler. |