[Effective C++]条款03:尽可能使用const

来源:互联网 发布:网络棋牌现金赌博平台 编辑:程序博客网 时间:2024/05/05 05:28

关键字const出现在星号*左边,表示被指物是常量;

如果出现在星号*右边,表示指针自身是常量;

如果出现在星号*两边,表示被指物和指针两者都是常量。

char greeting[] = “Hello”;  char *p = greeting;                 //non-const pointer, non-const data  const char *p = greeting;           //non-const pointer, const data  char *const p = greeting;           //const pointer, non-const data  const char *const p = greeting             //const pointer, const data  

声明迭代器为const就像声明指针为const一样,表示迭代器不得指向不同东西,但所指的值可以改动。

std::vector<int> vec;  const std::vector<int>::iterator iter = vec.begin();            //iter的作用像个T* const  *iter = 10                                          //没问题,改变iter所指物  ++iter;                                                 //错误! iter是const  const std::vector<int>::const_iterator cIter = vec.begin();     //cIter的作用像个const T*  *cIter = 10                                                     //错误! *cIter是const  ++cIter;                                                        //没问题,改变cIter 

将返回值声明为const,避免它被当作左值,预防不必要的赋值动作;

class Rational {…};  const Rational::operator* (const Rational& lhs, const Rational& rhs) ;
成员函数声明为const,确认该成员函数可作用于const 对象;

    一、使class接口比较容易被理解;

    二、使“操纵const对象”称为可能。


参数声明为const,避免它修改
成员函数声明为const,确认该成员函数可作用于const 对象(const对象只能调用const 成员)

编译器强制实时bitwise constness,但编写程序使应该使用“概念上的常量性”(conceptual constness)

当const和non-const成员函数有着实质等价的实现是,令non-const版本调用const版本可避免代码重复

0 0