Let's Complain the Irresponsible keyword 'const' in C++



as we were told, the 'const' methods of a C++ class will protect its members from being changed . it makes me so confident that 'const' methods are absolutely safe until someday i found a case which may be very often to occur but likely to be overlooked . by instinct i thought if C++ engaged that members are not to be changed, all the data will keep unchanged . also by instinct i give the same treat to the indirect data, say data involved by a pointer member. 

but C++ itself doesn't think so ! it only protect the member pointer, but exclude the data pointed by the pointer . 

similar rules to the methods of members . for direct members, their non-const methods are forbid to call, but no limitation if call by a pointer . 


for example :


class A
{
public:
    void set() {}
    void get() const {}
    int d;
};
class B
{
public:
    void func() const;
    A  a;
    A* p;
}
void B::func() const
{
    a.d = 0 ;   // not allowed
    a.set() ;   // not allowed
    a.get() ;   // allowed
    p = &a ;    // not allowed
    p->d = 0 ;  // allowed
    p->set() ;  // allowed
    p->get() ;  // allowed
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值