條款三:盡可能使用const(use const whenever possible)const允許你指定一個(gè)語(yǔ)義約束,而編譯器會(huì)強(qiáng)制實(shí)施這項(xiàng)約束。它允許你告訴編譯器和其他程序員某值應(yīng)該保持不變。有一條約束需要注意,那就是:如果const出現(xiàn)在*號(hào)的左邊,那就是說(shuō)被指物是常量;如果出現(xiàn)在星號(hào)右邊,則表示指針本身是常量;如果出現(xiàn)在兩邊,則被指物和指針都是常量。如果被指物是常量,則關(guān)鍵字const寫在類型的前面和類型之后,星號(hào)之前兩種所表示的語(yǔ)義是相同的。例如下面這兩種寫法是一樣的:void f1(const Widget* pw);void f2(Widget const * pw);const也可用來(lái)修飾STL中的迭代器。聲明迭代器為const就想聲明指針為const一樣(即T* const 指針),表示這個(gè)迭代器不得指向不同的東西。但它所指的東西的值是可以改變的。如果希望迭代器所指的東西不可改變(即模擬一個(gè)const T*指針),需要的是const_iterator:std::vector<int> vec;...const std::vector<int>::iterator iter = vec.begin();// same as T* const*iter = 10; //no problem++iter; //wrong!!std::vector<int>::const_iterator cIter = vec.begin();//same as const T**iter = 10; //wrong!!++iter; //no problem
const 最具威力(?)的用法是面對(duì)函數(shù)聲明時(shí)的應(yīng)用。在一個(gè)函數(shù)聲明式內(nèi),const可以和函數(shù)返回值,各參數(shù),函數(shù)自身(成員函數(shù))產(chǎn)生關(guān)聯(lián)。令函數(shù)返回一個(gè)常量值,往往可以降低因客戶錯(cuò)誤而造成的意外,而又不至于放棄安全性和高效性。例如,考慮有理數(shù)的operator*聲明式:class Rational(){...};const Rational operator* (const Rational & lhs, const Rational & rhs);也許你會(huì)說(shuō)為什么返回一個(gè)const對(duì)象?原因是如果不這樣別人可能實(shí)現(xiàn)這樣的暴行:Rational a,b,c;...(a*b)=c;下面,主要說(shuō)明const作用于成員函數(shù)。許多人都忽視了這么一個(gè)事實(shí),那就是如果兩個(gè)成員函數(shù)只是常量性不同,那么他們是可以重載的。考慮以下這個(gè)用來(lái)表示一大塊文字的class:
Things to Remember
Declaring something const helps compilers detect usage errors. const can be applied to objects at any scope, to function parameters and return types, and to member functions as a whole.
Compilers enforce bitwise constness, but you should program using conceptual constness.
When const and non-const member functions have essentially identical implementations, code duplication can be avoided by having the non-const version call the const version.
posted on 2008-12-09 23:00 Edmund 閱讀(270) 評(píng)論(0) 編輯 收藏 引用
Powered by: C++博客 Copyright © Edmund