设为首页 加入收藏

TOP

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

The wonderful thing about const is that it allows you to specify a semantic constraint — a particular object should not be modified — and compilers will enforce that constraint. It allows you to communicate to both compilers and other programmers that a value should remain invariant. Whenever that is true, you should be sure to say so, because that way you enlist your compilers’ aid in making sure the constraint isn’t violated.

The const keyword is remarkably versatile. Outside of classes, you can use it for constants at global or namespace scope (see Item 2), as well as for objects declared static at file, function, or block scope. Inside classes, you can use it for both static and non-static data members. For pointers, you can specify whether the pointer itself is const, the data it points to is const, both, or neither:

  1. char greeting[] = "Hello";  
  2. char *p = greeting;  // non-const pointer,  
  3.  // non-const data  
  4. const char *p = greeting;  // non-const pointer,  
  5.  // const data  
  6. char * const p = greeting;  // const pointer,  
  7.  // non-const data  
  8. const char * const p = greeting;  // const pointer,  
  9.  // const data 

This syntax isn’t as capricious as it may seem. If the word const appears to the left of the asterisk, what’s pointed to is constant; if the word const appears to the right of the asterisk, the pointer itself is constant; if const appears on both sides, both are constant .

When what’s pointed to is constant, some programmers list const before the type. Others list it after the type but before the asterisk. There is no difference in meaning, so the following functions take the same parameter type:

  1. void f1(const Widget *pw);  // f1 takes a pointer to a  
  2.  // constant Widget object  
  3. void f2(Widget const *pw);  // so does f2 

Because both forms exist in real code, you should accustom yourself to both of them.


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

评论

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