我有一本书,上面写着:

class Foo 
{
public:
    int Bar(int random_arg) const
    {
        // code
    }
};

这是什么意思?


在函数声明后用关键字const表示的“const函数”,使这个类函数更改类的成员变量成为编译器错误。但是,在函数内部读取类变量是可以的,但是在函数内部写入将会产生编译器错误。

Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit this pointer. So a method int Foo::Bar(int random_arg) (without the const at the end) results in a function like int Foo_Bar(Foo* this, int random_arg), and a call such as Foo f; f.Bar(4) will internally correspond to something like Foo f; Foo_Bar(&f, 4). Now adding the const at the end (int Foo::Bar(int random_arg) const) can then be understood as a declaration with a const this pointer: int Foo_Bar(const Foo* this, int random_arg). Since the type of this in such case is const, no modifications of member variables are possible.

可以放宽“const function”的限制,即不允许函数写入类的任何变量。为了允许一些变量是可写的,即使函数被标记为“const函数”,这些类变量被标记为关键字mutable。因此,如果一个类变量被标记为可变的,并且一个“const函数”写入这个变量,那么代码将被干净地编译,变量也可能被更改。(c++ 11)

通常在处理const关键字时,改变c++语句中const关键字的位置具有完全不同的含义。const的上述用法仅适用于将const添加到函数声明的括号后。

const在c++中是一个被过度使用的限定符:与指针结合使用时,语法和顺序通常不直接。关于const的正确性和const关键字的一些阅读:

Const正确性

c++ 'const'声明:Why & How


和这个问题类似。

本质上,这意味着Bar方法不会修改Foo的不可变成员变量。


Bar保证不会更改正在对其调用的对象。例如,请参阅c++常见问题解答中有关const正确性的部分。


我总是觉得在概念上更容易认为你正在使this指针const(这几乎是它所做的)。


考虑两个类类型变量:

class Boo { ... };

Boo b0;       // mutable object
const Boo b1; // non-mutable object

现在你可以在b0上调用Boo的任何成员函数,但只能在b1上调用const限定的成员函数。


函数不能通过你给它的指针/引用改变它的形参。

每当我需要思考这个问题时,我就会翻到这一页:

http://www.parashift.com/c++-faq-lite/const-correctness.html

我相信在Meyers的“更有效的c++”中也有很好的一章。