设为首页 加入收藏

TOP

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

STL iterators are modeled on pointers, so an iterator acts much like a T* pointer. Declaring an iterator const is like declaring a pointer const (i.e., declaring a T* const pointer): the iterator isn’t allowed to point to something different, but the thing it points to may be modified. If you want an iterator that points to something that can’t be modified (i.e., the STL analogue of a const T* pointer), you want a const_iterator:

  1. std::vector vec;  
  2. ...  
  3. const std::vector::iterator iter = // iter acts like a T* const  
  4.    vec.begin();  
  5. *iter = 10; // OK, changes what iter points to  
  6. ++iter; // error! iter is const  
  7. std::vector::const_iterator cIter = //cIter acts like a const T*  
  8.    vec.begin();  
  9. *cIter = 10; // error! *cIter is const  
  10. ++cIter; // fine, changes cIter 

Some of the most powerful uses of const stem from its application to function declarations. Within a function declaration, const can refer to the function’s return value, to individual parameters, and, for member functions, to the function as a whole.

Having a function return a constant value often makes it possible to reduce the incidence of client errors without giving up safety or efficiency. For example, consider the declaration of the operator* function for rational numbers that is explored in Item 24:

  1. class Rational { ... };  
  2. const Rational operator*(const Rational& lhs, const Rational& rhs); 

Many programmers squint when they first see this. Why should theresult of operator* be a const object Because if it weren’t, clientswould be able to commit atrocities like this:

  1. Rational a, b, c;  
  2. ...  
  3. (a * b) = c;  // invoke operator= on the  
  4.  // result of a*b! 

I don’t know why any programmer would want to make an assignment to the product of two numbers, but I do know that many programmers have tried to do it without wanting to. All it takes is a simple typo (and a type that can be implicitly converted to bool):

  1. if (a * b = c) ...  // oops, meant to do a comparison! 

现代编译器都会提醒你,这里有可能应该写“==”而不是“=”。如果你确信你需要“=”,而不是“==”,可以再加一层括号来避免编译器的问责。


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

评论

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