设为首页 加入收藏

TOP

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

Such code would be flat-out illegal if a and b were of a built-in type. One of the hallmarks of good user-defined types is that they avoid gratuitous incompatibilities with the built-ins (see also Item 18), and allowing assignments to the product of two numbers seems pretty gratuitous to me. Declaring operator*’s return value const prevents it, and that’s why it’s The Right Thing To Do in this case.

There’s nothing particularly new about const parameters — they act just like local const objects, and you should use both whenever you can. Unless you need to be able to modify a parameter or local object, be sure to declare it const. It costs you only the effort to type six characters, and it can save you from annoying errors such as the “I meant to type ‘==’ but I accidently typed ‘=’” mistake we just saw.

const Member Functions

The purpose of const on member functions is to identify which member functions may be invoked on const objects. Such member functions are important for two reasons. First, they make the interface of a class easier to understand. It’s important to know which functions may modify an object and which may not. Second, they make it possible to work with const objects. That’s a critical aspect of writing efficient code, because, as Item 20 explains, one of the fundamental ways to improve a C++(www.cppentry.com) program’s performance is to pass objects by reference- to-const. That technique is viable only if there are const member functions with which to manipulate the resulting const-qualified objects.


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

评论

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