c++ - 如何理解内存中的常量变量。 C++

标签 c++ pointers constants

如果我有一个常量变量,它是否存储在与非常量变量不同的内存空间中?我在这个程序中遇到了一些奇怪的事情。

    //--------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 也是相同的地址,但它们的值对称变化。为什么?

最佳答案

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

关于c++ - 如何理解内存中的常量变量。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5987817/

相关文章:

c++ - 我可以在命名空间中重新定义内置类型吗?

c++ 压缩库 - Deflate 或 Gzip

c - C 字符串中的 %d 个指针到整数的转换?

.net - .Net 是否有任何内置常量用于常见数字,如百万、十亿等?

c++ - 函数更改 const 对象

c++ - 如何将包含在字符(字节)中的十六进制值转换为整数?

c++ - 遍历列表 vector

c - 二进制 * 的无效操作数(有 ‘ab {aka struct a}’ 和 ‘ab * {aka struct a *}’ )

c - 是否可以 free() 函数返回的指针?

c++ - 编译器如何决定调用哪个函数?