條款三:盡可能使用const(use const whenever possible)const允許你指定一個語義約束,而編譯器會強制實施這項約束。它允許你告訴編譯器和其他程序員某值應該保持不變。有一條約束需要注意,那就是:如果const出現在*號的左邊,那就是說被指物是常量;如果出現在星號右邊,則表示指針本身是常量;如果出現在兩邊,則被指物和指針都是常量。如果被指物是常量,則關鍵字const寫在類型的前面和類型之后,星號之前兩種所表示的語義是相同的。例如下面這兩種寫法是一樣的:void f1(const Widget* pw);void f2(Widget const * pw);const也可用來修飾STL中的迭代器。聲明迭代器為const就想聲明指針為const一樣(即T* const 指針),表示這個迭代器不得指向不同的東西。但它所指的東西的值是可以改變的。如果希望迭代器所指的東西不可改變(即模擬一個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 最具威力(?)的用法是面對函數聲明時的應用。在一個函數聲明式內,const可以和函數返回值,各參數,函數自身(成員函數)產生關聯。令函數返回一個常量值,往往可以降低因客戶錯誤而造成的意外,而又不至于放棄安全性和高效性。例如,考慮有理數的operator*聲明式:class Rational(){...};const Rational operator* (const Rational & lhs, const Rational & rhs);也許你會說為什么返回一個const對象?原因是如果不這樣別人可能實現這樣的暴行:Rational a,b,c;...(a*b)=c;下面,主要說明const作用于成員函數。許多人都忽視了這么一個事實,那就是如果兩個成員函數只是常量性不同,那么他們是可以重載的。考慮以下這個用來表示一大塊文字的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) 評論(0) 編輯 收藏 引用
Powered by: C++博客 Copyright © Edmund