您的位置:首页 > 编程语言 > C语言/C++

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

2016-04-09 19:17 507 查看
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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: