如何理解内存中的常量变量。 C ++ [英] How can understand a constant variable in memory. C++

查看:171
本文介绍了如何理解内存中的常量变量。 C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个常量变量,它是存储在一个单独的内存空间从非常量变量?我在这个程序中遇到了一些奇怪。

If I have a constant variable, is it stored in a seperate memory space from non-constant variables? I have encounter some odd in this program.

    //--------assign a const value to non-const value-------
const int cst_a = 5;
int* ptra = const_cast<int*>(&cst_a);

cout<<&cst_a<<" "<<ptra<<endl; // same address

*ptra = 6;

cout<<*ptra<<" "<<cst_a<<endl; // same address with different value

//--------assign a non-const value to const value-------

int b = 50;
const int* cst_ptr_b = &b;

cout<<cst_ptr_b<<" "<<&b<<endl; // also same address

b = 55;
cout<<b<<" "<<*cst_ptr_b<<endl; // same address with same value

return 0;

在第一种情况下,& cst_a和ptra具有相同的内存地址,单独。在第二种情况下,cst_ptr_b和& b也是相同的地址,但是它们的值对称地改变。为什么?

In the first case, &cst_a and ptra has the same memory address, but their value can change seperately. In the second case, cst_ptr_b and &b are also same address, but their value change symetrically. Why?

推荐答案

它可能存储在无法修改的内存区域。因此,您的 const_cast 会导致未定义的行为。

It may be stored in a memory area that can't be modified. Because of this, your const_cast results in undefined behavior.

这篇关于如何理解内存中的常量变量。 C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆