设为首页 加入收藏

TOP

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

The solution is simple: take advantage of C++(www.cppentry.com)’s const-related wiggle room known as mutable. mutable frees non-static data members from the constraints of bitwise constness:

  1. class CTextBlock {  
  2. public:  
  3.   ...  
  4.   std::size_t length() const;  
  5. private:  
  6.   char *pText;  
  7.   mutable std::size_t textLength;  // these data members may  
  8.   mutable bool lengthIsValid;  // always be modified, even in  
  9. };  // const member functions  
  10. std::size_t CTextBlock::length() const 
  11. {  
  12.   if (!lengthIsValid) {  
  13.     textLength = std::strlen(pText); // now fine  
  14.     lengthIsValid = true;  // also fine  
  15.   }  
  16.   return textLength;  

Avoiding Duplication in const and Non-const Member Functions

mutable is a nice solution to the bitwise-constness-is-not-what-I-hadin- mind problem, but it doesn’t solve all const-related difficulties. For example, suppose that operator[] in TextBlock (and CTextBlock) not only returned a reference to the appropriate character, it also performed bounds checking, logged access information, maybe even did data integrity validation. Putting all this in both the const and the non-const operator[] functions (and not fretting that we now have implicitly inline functions of nontrivial length — see Item 30) yields this kind of monstrosity:

  1. class TextBlock {  
  2. public:  
  3.   ...  
  4.   const char& operator[](std::size_t position) const 
  5.   {  
  6.     ...  // do bounds checking  
  7.     ...  // log access data  
  8.     ...  // verify data integrity  
  9.     return text[position];  
  10.   }  
  11.   char& operator[](std::size_t position)  
  12.   {  
  13.     ...  // do bounds checking  
  14.     ...  // log access data  
  15.     ...  // verify data integrity  
  16.     return text[position];  
  17.   }  
  18. private:  
  19.   std::string text;  
  20. }; 

Ouch! Can you say code duplication, along with its attendant compilation time, maintenance, and code-bloat headaches Sure, it’s possible to move all the code for bounds checking, etc. into a separate member function (private, naturally) that both versions of operator[] call, but you’ve still got the duplicated calls to that function and you’ve still got the duplicated return statement code.


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

评论

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