根据我的理解,mutable
取消了变量的constness
Class A {
void foo() const {
m_a = 5;
}
mutable int m_a;
};
还有 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;
}
那么,是什么改变了彼此?
谢谢
最佳答案
const_cast
无法取消对象的常量性。 const_cast
只能从对象的访问路径 中移除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
上述内容合法有效的唯一原因是 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 !!!
C++ 语言不允许您修改常量对象,const_cast
在这里完全无能为力,无论您如何使用它。
mutable
是完全不同的东西。 mutable
创建一个可以合法修改的数据文件,即使包含的对象被声明为 const
。从这个意义上说,mutable
确实允许您修改常量对象的[某些指定部分]。另一方面,const_cast
不能做那样的事情。
关于c++ - const_cast VS 可变的?有什么不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11457953/