问题描述
根据我的理解, mutable
取消变量
From my understanding , mutable
cancels the constness
of a variable
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;
}
那么,什么改变了一个呢?
So , what changes one from the other ?
感谢
推荐答案
const_cast
无法取消对象的constness。
const_cast
只能从对象的访问路径中删除const。访问路径是指向对象的指针或引用。从访问路径中删除常量对对象本身绝对没有影响。即使您使用 const_cast
删除访问路径的常量,仍然不一定给您修改对象的权限。无论你能做到还是不依赖于对象本身。如果是const,则不允许修改它,任何尝试都将导致未定义的行为。
const_cast
cannot cancel constness of an object. const_cast
can only remove constness from an access path to an object. Access path is a pointer or a reference to an object. Removing the constness from the access path has absolutely no effect on the object itself. Even if you use const_cast
to remove the constness of the access path, that still does not necessarily give you the permission to modify the object. Whether you can do it or not still depends on the object itself. If it is const, you are not allowed to modify it and any attempts to do so will result in undefined behavior.
例如,这说明了 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
实际上是一个非常量对象,我们知道它的事实。
The only reason the above is legal and valid is the fact that i
is actually a non-constant object, and we know about it.
如果原始对象真的是常数,上述代码将产生未定义的行为:
If the original object was really constant, then the above code would produce undefined behavior:
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 $
C++ language does not allow you to modify constant objects and const_cast
is completely powerless here, regardless of how you use it.
mutable
是完全不同的东西。 mutable
创建可以合法修改的数据字段,即使包含对象声明为 const
。在这个意义上, mutable
允许你修改常量对象的某些指定部分。 const_cast
,另一方面,不能做这样的事情。
mutable
is a completely different thing. mutable
creates a data filed that can be legally modified even if the containing object is declared const
. In that sense mutable
does allow you to modify [some designated parts of] constant objects. const_cast
, on the other hand, can't do anything like that.
这篇关于const_cast VS mutable?有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!