Item 3: Use const whenever possible.(6)

2013-10-07 14:26:24 · 作者: · 浏览: 64

This leads to the notion of logical constness. Adherents to this philosophy argue that a const member function might modify some of the bits in the object on which it’s invoked, but only in ways that clients cannot detect. For example, your CTextBlock class might want to cache the length of the textblock whenever it’s requested:

  1. class CTextBlock {  
  2. public:  
  3.   ...  
  4.   std::size_t length() const;  
  5. private:  
  6.   char *pText;  
  7.   std::size_t textLength;  // last calculated length of textblock  
  8.   bool lengthIsValid;  // whether length is currently valid  
  9. };  
  10. std::size_t CTextBlock::length() const 
  11. {  
  12.   if (!lengthIsValid) {  
  13.     textLength = std::strlen(pText); // error! can’t assign to textLength  
  14.     lengthIsValid = true;  // and lengthIsValid in a const  
  15.   }  // member function  
  16.   return textLength;  

This implementation of length is certainly not bitwise const — both textLength and lengthIsValid may be modified — yet it seems as though it should be valid for const CTextBlock objects. Compilers disagree. They insist on bitwise constness. What to do