FAQ 14.05 Is const correctness tedious?

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 

(1) Wrong way to document the restriction

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 

(1) Right way to document the restriction

This form of documentation is succinct, in one place, and can be verified and exploited by the compiler.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net