const_cast会浪费额外的内存吗?
让我们先看看示例。
#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;
}
我不知道它在内存体系结构中的成就。似乎编译器在堆栈中占据了额外的内存空间,因此我们可以跟踪“原始” constant
其值为1
,以及在值为100
的堆栈。是吗?因此,const_cast
确实会因为初学者可能不会期望的是消耗额外的内存吗?
Let's see the example first.
#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;
}
I don't know how it achieved in the memory architecture. It seems that the compiler have occupied extra memory space in the stack so that we can keep track of the "original" constant
whose value is 1
, and a new memory location in the stack whose value is 100
. Is it? So will const_cast
indeed consume extra memory as a beginner might not first expect?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这
是不确定的。您不能更改
const int
的值。您可以抛弃constness,但您不可能修改恒定的东西。正确使用const演员将是:
这里没有使用“额外的内存”。
代码中发生的事情可能是编译器看到
并且编译器“知道”
const int constant
在初始化后不可能更改其价值,因此它可以用This
is undefined. You cannot change the value of a
const int
.You can cast away constness but you cannot possibly modify something that is constant. A correct usage of the const cast would be for example:
No "extra memory" is being used here.
What happens in your code is probably that the compiler sees
And the compiler "knows" that
const int constant
cannot possibly change its value after initialization, hence it can replace that line with