c++ const class trick

<<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]来访问是就会引入错误。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值