const的作用及使用细节
- const能在编译器阶段保证对象不能被修改。
- const能对全局变量、局部静态变量,类属成员变量,指针进行约束。
char greeting[]="Hello";
char* p=greeting;
const char*p=greeting;//指针所指的内容是常量
char* const p=greeding;//指针是常量
const char* const p=greeting;//指针和指针所指的内容都是常量
void f1(const int* p);
void f2(int const*p);//上述两个const的效果一样,都是指向一个常对象的指针。
const在迭代器中的使用
迭代器相当于一个指针,const修饰迭代器就是说这个迭代器是不可修改的,但是迭代器所指的内容是可以被修改的。
std::vector vec;
const std::vector::iterator iter=vec.begin();
*iter=10;//迭代器所指的内容可以被修改
++iter;//错误,迭代器被声明称const了,不可以被修改
但是要注意和const_iterator区别开
std::vector vec;
std::vector::const_iterator clter=vec.begin();
*clter=10;//错误,迭代器所指的内容不可以被修改
++clter;//正确,迭代器可以被修改
const修饰函数返回值和函数参数
class Rational{};
const Rational operator*(const Rational& lhs,const Rational& rhs);
上述将返回值声明为const,可以避免如下问题:
Rational a,b,c;
(a*b)=c;//如果是内置类型,这肯定是非法的,因为左边必须是可以被修改的左值。用户自定义类型也要如此。
const 成员函数
- 对于类属成员函数,使用const的优势在于:
- 可以知道const对象可以调用哪些成员函数。
- const函数使得类的接口更容易被理解,知道哪些函数可以改变对象哪些不可以
- 按const引用传递对象可以提高程序的效率。const成员函数要处理const修饰的对象。
- 函数可以通过是否加上const进行重载
class TextBlock
{
public:
const char&operator[](std::size_t positioin) const
{return text[position];}
char&operator[](std::size_t position)
{return text[position];}
private:
std::string text;
};
int main(){
TextBlock tb(“Hello”);
std::cout<tb[0];//调用非常量性运算符[]
Const TextBlock ctb(“World”);
std::cout<<ctb[0];//调用常量性运算符[]
}
const的两个派别
派别一
- 创建一个const对象的时候,调用了对象的const成员函数,但是值仍然被修改了。
- 原因出在一个成员函数修改指针指向的内容没有表现出常量性
class CTextBlock {
public:
CTextBlock( char* s) {
pText = s;
}
char& operator[](std::size_t position) const {
return pText[position];
}
private:
char *pText;
};
int main(){
const CTextBlock cctb("Hello"); //声明一个常对象
char *pc = &cctb[0]; //调用常运算符[],获得一个指向c风格的字符串指针
*pc = 'j';//修改了数据
}
派别二
#include<cstddef>
#include<string>
class CTextBlock {
public:
std::size_t length() const;
private:
char* pText;
mutable std::size_t textLength;
mutable bool lengthIsValid;//使用mutable修饰。表示即使在const成员函数,也可以对其修改
};
std::size_t CTextBlock::length() const
{
if (!lengthIsValid) {
textLength = strlen(pText);
lengthIsValid = true;//如果不是mutable,则会报错
}
return textLength;
}
参考资料
- 迈耶斯. Effective C++ : 改善程序与设计的55个具体做法 : 55 specific ways to improve your programs and designs[M]. 北京 : 电子工业出版社, 2011