MSDN 写道:您不能使用 const_cast 运算符直接覆盖常量变量的常量状态 :-(。
const_cast
允许您const
从指针中删除说明符,但它不会影响值本身的“常量状态”。编译器可能决定将该值放入只读内存(嗯,它是 const!),然后尝试修改它,即使通过const_cast
,也可能导致访问冲突。
这是一个代码片段:
static const int A = 1; // it's constant, it might appear on a read-only memory page
static int B = 2; // it's a regular variable
const int* pA = &A; // a const pointer
int* pB1 = &B; // a pointer
const int* pB2 = &B; // a const pointer to regular variable
*pA = 0; // Compiler error, we are not allowed to modify const
*const_cast<int*>(pA) = 1; // Runtime error, although const specifier is stripped from the variable, it is still on read-only memory and is not available for updates
*pB1 = 2; // OK
*pB2 = 3; // Compiler error, we are not allowed to modify const
*const_cast<int*>(pB2) = 4; // OK, we stripped const specifier and unlocked update, and the value is availalbe for update too because it is a regular variable
也就是说,const_cast
在编译期间删除 const 说明符,但是改变底层内存的访问模式并不是它的目的、权限或设计。