C++改善_2016_11_23

来源:互联网 发布:练文笔的软件 编辑:程序博客网 时间:2024/05/29 17:43
//rule03: 尽可能使用const


//const,允许你指定一个“不该被改动 ”的对象
//编译器会帮你强制实施这个约束
//只要这是事实,你就该确实说出来,这样就能获得编译器的帮助,确保这个约束不被违反


//在STL中有两种case:
//1. 声明迭代器为const就像声明指针为const一样,表示这个迭代器不得指向不同的东西,但它所指的东西的值可以改动
std::vector<int> vec;
...
const std::vector<int>::iterator iter = vec.begin(); //such as T* const
*iter = 10; //没问题,改变iter所指物 
++iter; //错误!iter是const


//如果你希望迭代器所指的东西不可被改动,就需要的是const_iterator
std::vector<int>::const_iterator cIter = vec.begin();
*cIter = 10; //错误 *cIter是const
++CIter;  //没问题该表cIter


const最具威力的用法是面对函数声明时的应用
class Rational {...};
const Rational operator*(const Rational &lhs, const Rational &rhs);
这样做可以避免诸如if(a*b = c).....的错误


在const成员函数内,如果你想赋值给成员变量,就在成员变量声明时最前面加mutable


class Text{
public:
...
const char& operator[](std::size_t position) const
{
...
...
...
return text[position];
}

char& operator[](std::size_t position)
{
...
...
...
return text[position];
}
};




==>可优化为
const char& opertor[](std::size_t position) const
{
...
...
...
return text[position];
}

char& operaotr[](std::size_t position)
{
return 
const_cast<char &>(
static_cast<const TextBlock&)(*this)[position]
);



//反向做法就不行
//记住, const成员函数承诺绝对不改变其对象的逻辑状态。


//将某些东西声明为const可帮助编译器侦测处错误用法。const可被施加于任何作用域内的对象,函数参数,函数返回类型,成员函数本体
//编译器强制实施bitwise constness, 但你编写程序时应该使用"logical constness" 
//当const和non-const成员函数有着实质等价的实现时,令non-const版本调用const版本可避免代码重复。 
 






























 
 
0 0
原创粉丝点击