<<Effective c++>>建议我们使用const来为程序引入限制,这一方面是为了提醒代码阅读者另一方面也可以让编译器检查程序代码对const修饰的元素的非法修改。但是添加了const修饰符之后,也会带来一些非常tricky的变化,下面我就着重说明其中的一点。
class A {
public:
void f() {}
void g() const {}
};
const A a;
a.f();//wrong!
a.g();//correct!
这里a.f()的成员函数调用是非法的,如果在gcc下编译给代码片则会报如下错误:error: passing ‘const A’ as ‘this’ argument of ‘void A::f()’ discards qualifiers [-fpermissive]
原因已经很明显了,f函数的第一个参数为this,其类型为A *,与此相对g的this的类型为const A*,这里的a为const A类型,当调用a的f函数时,传递给f的第一个参数类型是const A*,这与f的第一个参数类型不匹配,从而引发了错误。下面引用一段更加权威的解释(from the language specification):
9.3.2 The this pointer
In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*. [ Note: thus in a const member function, the object for which the function is called is accessed through a const access path. —end note ]
最后说明一个例子,当我们使用模板是经常将函数的参数声明为const类型的引用,例如在传递一个unordered_map时会将其声明为const unordered_map<sometype> &mymap
而为了方便访问unordered_map类重载了[]操作符,但[]操作符重载函数是非const类型的,此时使用mymap[key]来访问是就会引入错误。