effective c++ 条款03 尽可能的使用const (const 的魅力)

刚进入IT程序员这一行有一年的时间了,现在是c++学了点皮毛,最近又想学习python,又想学习java,我否定了自己的想法,还是应该深入的学习c++的stl,以及boost,但摆在前面的还有设计模式,不说了还是塌下心来认真的读几本c++的经典才是最实在的,言归正传。

1.const的基本使用,修饰变量,修饰函数参数。

   1)修饰变量

char greeting[] = "Hello";
char name[] = "cxue";
char* const p = greeting;
p = name;  //不合法的,地址不能改变 
*p= 'x';      //合法的可以改变它的值   
char greeting[] = "Hello";
char name[] = "cxue";
const char* p = greeting;
p = name;  //合法的它的地址可以改变
*p= 'x';      //不合法的值是不可以改变的

2)修饰函数参数时

void display(const char* str)
{
 *str = 'x'; //不合法的,不能给*str赋值。
 cout << str <<endl;

}
void display(char* const str)
{
    *str = 'x';//这样确实合法的,在使用的时候要注意呀。 
    cout << str <<endl;

}

还有一点:

void display(const char*  str)
void display(char const *str) //这两个是等同的

const还可以修饰函数的返回值主要表现在运算符重载上,可以防止程序员意外修改。

class Num{...};
const Num operator*(const Num &lhs,const Num &rhs);

Num a, b, c,;
本意想写成:
if(a*b == c)
{};
却不小心写成了:
if(a*b = c)
{};

使用const可以有效的弥补了编译器不能察觉的错误。

2、const 在STL中的使用:

#include <iostream>
#include <vector>
//using namespace std;
int main()
{
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    const std::vector<int>::iterator it = vec.begin();
    it++;       //不合法的,it地址是个不能变的变量
    *it = 4;    //合法的

    std::vector<int>::const_iterator it = vec.begin();
    it++;        //合法的
    *it = 5     //不合法的,it为const_iterator类型,it指向的值是不能被改变的。

    
}

3.const 用作于成员函数
const实施于成员函数有两个重要的意义,第一:我们可以知道哪个成员函数可以改变对象里的内容,第二,使操作“const 对象”成为了可能。

还有一个容易被人们忽略的一点是两个成员数如果只是常量性不同,可以被重载。

看一下demo:

#include <iostream>
#include <vector>
//using namespace std;

class TextBox{

private:
    std::string text;
public:
    TextBox(std::string str):text(str){};
    ~TextBox(){};
    const char& operator[] (int position) const
    {
        std::cout << "const"<<std::endl;
        return text[position];
    };
    char& operator[] (int position)                 //注意返回的是char& ,返回char类型是不合法的,如果那样意味着我们将修改一个text[position]的副本。
    {
        std::cout << "non-const" <<std::endl;
        return text[position];
    };
};
int main()
{
    const TextBox box("hello,world");
    TextBox box2("cxue");
    std::cout<< box[0] << std::endl;
    std::cout<< box2[1] << std::endl;
    
    getchar();
    
}

运行结果如下:

4.一个与const相关的摆动场:mutable(可变)。

mutable可以理解为可以释放掉出non-static成员变量的bitwise constness的约束:

class CTextBlock{
public:
    int length()const;
private:
    char* pText;
    mutable int textLength;
    mutable bool lengthIsValid;
};
int CTextBlock::length()const
{
    if(!lengthIsValid)
    {
        textLength = std::strlen(pText);
        lengthIsValid = true;
    }
    return textLength;

}
原文地址:https://www.cnblogs.com/onlycxue/p/3042825.html