条款03:尽可能使用 const

Use const whenever possible.

const 约束

const 可以指定一个语义约束(指定一个不该被改动的对象),而编译器会强制实施这项约束。

面对指针,const 可以指出指针本身、指针所指物、或两者都(或都不)是 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 出现在星号左边,表示被指物是常量;如果出现在星号右边,表示指针自身是常量;如果出现在星号两边,表示被指物和指针都是常量。

STL 迭代器系以指针为根据塑模出来,所以迭代器的作用就像个 T* 指针,声明迭代器为 const 就像声明指针为 const 一样,表示这个迭代器所指的东西不可被改动。

令函数返回一个常量值,往往可以降低因客户错误而造成的问题,并且不会降低安全性和高效性,例如:

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

Rational a, b, c;
...
if (a * b = c) ... // 如果程序员无意中编写了这样的语句,编译器会直接报错

const 成员函数

有两种 const 成员函数:

  • const T func() 表示返回的为 const 类型;

  • T func() const 表示函数不能修改其成员变量;

两个成员函数如果只是常量性(constness)不同,是可以被重载的,例如:

class TextBlcok {
public:
    const char& operator[](std::size_t position) const {
        return text[position];
    }
    char& operator[](std::size_t position) {
        return tex[position];
    }
private:
    std::string text;
};

TextBlock tb("Hello");
std::cout << tb[0];     // 调用 non-const TextBlock::operator[]
const TextBlock ctb("Hello");
std::cout << ctb[0];    // 调用 const TextBlock::operator[]

真实程序中 const 对象大多用于 passed by pointer-to-const 或者 passed by reference-to-const 的传递结果:

void print(const TextBlock& ctb) {
    std::cout << ctb[0];    // 调用 const TextBlock::operator[]
}

成员函数如果是 const 意味着什么?这里有流行的概念:bitwise constness(又称 physical constness)和 logical constness。

bitwise constness 认为,成员函数只有在不更改对象中任何成员变量时,才可以说是 const。不过很多成员函数虽然不具备 const 性质,但是却能通过 bitwise 测试,例如:

class CTextBlock {
public:
    char& operator[](std::size_t position) const {
        return pText[position];
    }
private:
    char* pText;
};

logical constness 主张一个 const 成员函数可以修改它所处理的对象内的某些 bits,但只有在客户端侦测不出的情况下才可以。但有时候符合 logical constness 的 const 成员函数并不能通过编译器,这时需要用 mutable(可变性)释放掉 non-static 成员变量的 bitwise constness 约束。

class CTextBlock {
private:
    mutable std::size_t textLength;
};

在 const 和 non-const 成员函数中避免重复

如果 const 成员函数和 non-const 成员函数中有大量重复的代码,应该使用 non-const 版本调用 const 版本:

class TextBlock {
public:
    const char& operator[](std::size_t position) const {}
    char& operator[](std::size_t position) {
        return const_cast<char&>(                    // 将 op[] 返回值的 const 转除
            static_cast<const TextBlock&>(*this)     // 为 *this 加上 const
                [position]                           // 调用 const op[]
            );
    }
};

令 const 版本调用 non-const 版本以避免重复是不合理的,因为 const 成员函数承诺绝不改变其对象的逻辑状态,non-const 成员函数却没有这般承诺,如果在 const 函数内调用 non-const 函数,就是冒险对承诺不改动的对象进行改动。

Last updated

Was this helpful?