根据我的理解,mutable取消constness变量
Class A {
void foo() const {
m_a = 5;
}
mutable int m_a;
};
Run Code Online (Sandbox Code Playgroud)
但是const_cast:
void print (char * str)
{
cout << str << endl;
}
int main () {
const char * c = "this is a line";
print ( const_cast<char *> (c) );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
那么,是什么改变了另一个呢?
谢谢
AnT*_*AnT 19
const_cast无法取消对象的常量.const_cast只能从访问路径中删除constness 到对象.访问路径是指针或对象的引用.从访问路径中删除constness对对象本身完全没有影响.即使您使用const_cast删除访问路径的常量,仍然不一定授予您修改对象的权限.是否可以做到仍取决于对象本身.如果它是const,则不允许您修改它,任何尝试这样做都将导致未定义的行为.
例如,这说明了它的预期用途 const_cast
int i = 5; // non-constant object
const int *p = &i; // `p` is a const access path to `i`
// Since we know that `i` is not a const, we can remove constness...
int *q = const_cast<int *>(p);
// ... and legally modify `i`
*q = 10;
// Now `i` is 10
Run Code Online (Sandbox Code Playgroud)
上述合法且有效的唯一原因是事实上它i实际上是一个非常数对象,我们知道它.
如果原始对象确实是常量,那么上面的代码会产生未定义的行为:
const int j = 5; // constant object
const int *p = &j; // `p` is a const access path to `j`
int *q = const_cast<int *>(p); // `q` is a non-const access path to `j`
*q = 10; // UNDEFINED BEHAVIOR !!!
Run Code Online (Sandbox Code Playgroud)
const_cast无论你如何使用它,C++语言都不允许你修改常量对象,并且在这里完全无能为力.
mutable是完全不同的事情.mutable即使声明了包含对象,也会创建一个可以合法修改的数据字段const.从这个意义上讲,mutable它允许你修改[常量对象的某些指定部分].const_cast另一方面,不能做那样的事情.