如何理解内存中的常量变量。 C++
如果我有一个常量变量,它是否与非常量变量存储在单独的内存空间中?我在这个程序中遇到了一些奇怪的情况。
//--------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也是相同的地址,但是它们的值对称地变化。为什么?
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;
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它可能存储在无法修改的内存区域中。因此,您的
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.恭喜,
*ptra = 6;
是未定义的行为。 :)不允许通过指针或引用写入常量值。这是因为常量对象可能(并且很可能会)被放入常量内存区域。
Congrats,
*ptra = 6;
is undefined behaviour. :)You are not allowed to write to a constant value, not through pointer, not through reference. This is because a constant object might (and most likely will) be put into the constant memory area.
这取决于您在常量中存储的值。
尝试修改只读区域是未定义的行为(您已在代码中使用
const_cast
完成了此操作)其他情况是,
It depends on what value you store in the constant.
Trying to modify read only area is Undefined Behavior (which you have done in your code using
const_cast
)Other scenario is,
问题在于示例#1 中发生的显式类型转换。 C++ 让你这样做,因为 const int* 和 int* 是不同的类型,并且编译器可以自由选择将常量存储在可写或不可写内存中,从而导致这种未定义的行为,如前面的帖子中所述。
The problem is the explicit type casting that is taking place in example #1. C++ let's you do this and since const int* and int* are different types along with the compilers free choice to store constants in either writeable or non-writeable memory makes this undefined behaviour, as said in earlier posts.