据我了解,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;
}
那么,两者有何不同呢?
Thanks
const_cast
无法取消对象的常量性。const_cast
只能从一个中删除常量访问路径到一个物体。访问路径是对象的指针或引用。从访问路径中删除常量对对象本身绝对没有影响。即使你使用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
,另一方面,不能做这样的事情。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)