DiscussionConstants simplify code because you only have to look at where the constant is defined to know its value everywhere. Consider this code: void Fun( vector<int>& v ) { // … const size_t len = v.size(); // … 30 more lines … } When seeing len's definition above, you gain instant confidence about len's semantics throughout its scope (assuming the code doesn't cast away const, which it should not do; see below): It's a snapshot of v's length at a specific point. Just by looking up one line of code, you know len's semantics over its whole scope. Without the const, len might be later modified, either directly or through an alias. Best of all, the compiler will help you ensure that this truth remains true. Note that const is not deep. For example, consider a class C that has a member of type X*. In C objects that are const, the X* member is also constbut the X object that is pointed to is not. (See [Saks99].) Implement logical constness with mutable members. When a const member function of a class legitimately needs to modify a member variable (i.e., when the variable does not affect the object's observable state, such as cached data), declare that member variable mutable. Note that if all private members are hidden using the Pimpl idiom (see Item 43), mutable is not needed on either the cached information or the unchanging pointer to it. Yes, const is "viral"add it in one place, and it wants to propagate throughout your code as you call other functions whose signatures aren't yet const-correct. This is a feature, not a bug, and this quality greatly increases const's power even though it was unjustly demeaned in the days when const wasn't well understood and appreciated. Retrofitting an existing code base to make it const-correct takes effort, but it is worthwhile and likely to uncover latent bugs. Const-correctness is worthwhile, proven, effective, and highly recommended. Understanding how and where a program's state changes is vital, and const documents that directly in code where the compiler can help to enforce it. Writing const appropriately helps you gain a better understanding of your design and makes your code sturdier and safer. If you find it impossible to make a member function const, you usually gain a better understanding of the ways in which that member function might modify an object's state. You might also understand which data members bridge the gap between physical constness and logical constness, as noted in the following Examples. Never cast away const except to call a const-incorrect function, or in rare cases as a workaround for lack of mutable on older compilers. |