我们先看一下例子。
#include <iostream>
int main()
{
const int constant = 1;
const int* const_p = &constant;
int* modifier = const_cast<int*>(const_p);
*modifier = 100;
std::cout << "constant: " << constant << ", *const_p=" << *const_p;
//Output: constant: 1, *const_p=100
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我不知道它在内存架构上是如何实现的。看来编译器在堆栈中占用了额外的内存空间,以便我们可以跟踪值为constant的“原始” 1,以及堆栈中值为 的新内存位置100。是吗?那么,const_cast确实会消耗额外的内存,这是初学者可能没有想到的吗?
这
*modifier = 100;
Run Code Online (Sandbox Code Playgroud)
未定义。您无法更改 a 的值const int。
你可以抛弃常量,但你不可能修改常量的东西。const 强制转换的正确用法例如:
int not_constant = 1; // not const !!
const int* const_p = ¬_constant;
int* modifier = const_cast<int*>(const_p);
*modifier = 100; // ok because not_constant is not const
Run Code Online (Sandbox Code Playgroud)
这里没有使用“额外内存”。
你的代码中发生的事情可能是编译器看到的
std::cout << "constant: " << constant << ", *const_p=" << *const_p;
Run Code Online (Sandbox Code Playgroud)
并且编译器“知道”const int constant在初始化后不可能更改其值,因此它可以将该行替换为
std::cout << "constant: " << 1 << ", *const_p=" << *const_p;
Run Code Online (Sandbox Code Playgroud)