bar*_*rej 3 c++ const-cast c++11
在我在网上发现的下面的例子中,提到的一个优点const_cast是它允许一个常量函数改变类成员.这是一个问题.我们为什么要设置一个函数规则const,然后用该规则来破坏该规则const_cast?这不是作弊吗?最好不设置const功能吗?
#include <iostream>
using namespace std;
class student
{
private:
int roll;
public:
student(int r):roll(r) {}
// A const function that changes roll with the help of const_cast
void fun() const
{
( const_cast <student*> (this) )->roll = 5;
}
int getRoll() { return roll; }
};
int main(void)
{
student s(3);
cout << "Old roll number: " << s.getRoll() << endl;
s.fun();
cout << "New roll number: " << s.getRoll() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这确实是一个坏主意.除了说明函数的行为之外,它还允许您修改常量student对象的成员,从而提供未定义的行为.
通常,成员函数应该是constif,并且仅当它不修改对象的可观察状态时.所以在这种情况下,它不应该const.
有时,您可能希望特定成员可以在不会导致可观察到的更改的函数中进行修改; 例如,锁定互斥锁以访问共享数据,或缓存复杂计算的结果.在这种情况下,声明这些成员mutable,以便该类的其余部分仍然受到const-correctness的保护.