条款03 尽可能使用const

一、概述

使用const约束对象:可以获得编译器的帮助(指出相关出错的地方)

const与成员函数:const重载、转型、避免代码重复

 

二、细节

1. 为什么有些函数要返回const对象(看上去没必要)?

返回const对象:a * b = c;  //operator*()函数返回一个const对象,故该表达式错误

补充:我们的本意或许是a * b == c,此时返回const是没影响的,故返回const可以预防“没意思的赋值动作”

2. const成员函数不能避免对象被更改的情况

mutable成员变量可以更改,即使在const成员函数内

3. 两个成员函数因const相互重载,而函数体内代码重复

我们可以令non-const版本调用const版本,来避免代码重复

class A {
public:
	const char &operator[](size_t pos) const
	{
		...
		return text[pos];
	}
	char &operator[](size_t pos)
	{
		return const_cast<char&>(static_cast<const A&>(*this)[pos]);
	}
}; 

  

 

posted @ 2017-11-16 18:05  GGBeng  阅读(130)  评论(0编辑  收藏  举报