const_cast会浪费额外的内存吗?

发布于 2025-02-12 20:49:20 字数 596 浏览 1 评论 0原文

让我们先看看示例。

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

π浅易 2025-02-19 20:49:20

*modifier = 100;

是不确定的。您不能更改const int的值。

您可以抛弃constness,但您不可能修改恒定的东西。正确使用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

这里没有使用“额外的内存”。


代码中发生的事情可能是编译器看到

std::cout << "constant: " << constant << ", *const_p=" << *const_p;

并且编译器“知道” const int constant在初始化后不可能更改其价值,因此它可以用

std::cout << "constant: " << 1 << ", *const_p=" << *const_p;

This

*modifier = 100;

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:

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

No "extra memory" is being used here.


What happens in your code is probably that the compiler sees

std::cout << "constant: " << constant << ", *const_p=" << *const_p;

And the compiler "knows" that const int constant cannot possibly change its value after initialization, hence it can replace that line with

std::cout << "constant: " << 1 << ", *const_p=" << *const_p;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文