设为首页 加入收藏

TOP

Item 3: Use const whenever possible.(6)
2013-10-07 14:26:24 来源: 作者: 【 】 浏览:62
Tags:Item Use const whenever possible.

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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Item 3: Use const whenever poss.. 下一篇Item 4: Make sure that objects ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: