Item 3: Use const whenever possible
Concept
const communicates semantic constraints to compilers and other programmers. It can apply to:
- Pointers (
const char*vschar* const) - Iterators (
const_iterator) - Function return types and parameters
- Member functions (logical constness via
mutable)
Code Example
// const with pointers
const char* p1 = "Hello"; // pointer to const data
char* const p2 = buf; // const pointer to non-const data
// const member functions
class TextBlock {
public:
const char& operator[](std::size_t pos) const {
return text[pos];
}
char& operator[](std::size_t pos) {
return const_cast<char&>(
static_cast<const TextBlock&>(*this)[pos]
);
}
private:
std::string text;
};
Things to Remember
- Declaring something
consthelps compilers detect usage errors. - Compilers enforce bitwise constness, but you should program using logical constness.
- When
constand non-constmember functions have essentially identical implementations, the non-constversion can call theconstversion to avoid duplication.