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
}
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
}
相关文章推荐
- c++作业3
- C++泛型之求未知数组的长度
- C++实验三
- c++模板实现栈
- 2016年蓝桥杯C++/c B组答案
- Getting Started with C++ in Visual Studio
- C++类内存分布
- C语言超大数相加求和、加减乘除算法实现
- C语言常用转义字符表 和 ASCII码表完整版
- 递归和尾递归的比较,斐波那契
- 3.10 左值和右值 中英文对照(C++标准中文版 ISO/IEC 14882:2014)
- C++虚继承内存布局
- C语言编程“Hello,world”
- Google的c++代码规范
- 队列的C++实现
- C++中的exit()函数
- 希尔排序算法的C语言实现示例
- C++ 读写文件
- 初步学习C++中的继承关系
- C++右值引用