我试图更改一个变量的值,该变量定义为int const,如下所示.
const int w = 10;
int* wp = const_cast <int*> (&w);
*wp = 20;
Run Code Online (Sandbox Code Playgroud)
w的值没有改变,即使在赋值之后仍然是10,尽管它表明w和wp都指向同一个内存位置.但是我可以更改w的值,如果在声明时定义如下
int i = 10;
const int w = i;
Run Code Online (Sandbox Code Playgroud)
如果我改变i的声明使其成为常量
const int i = 10;
Run Code Online (Sandbox Code Playgroud)
w的值不会改变.
在第一种情况下,为什么w的值没有改变,即使w和wp指向相同的内存位置[这是我打印地址时的印象]
与编译器有什么不同,它以不同的方式处理这两种情况?
有没有办法确保w不会失去常数,无论它的定义方式如何?
#include <iostream>
using namespace std;
int main() {
const int N = 22;
int * pN = const_cast<int*>(&N);
*pN = 33;
cout << N << '\t' << &N << endl;
cout << *pN << '\t' << pN << endl;
}
Run Code Online (Sandbox Code Playgroud)
22 0x22ff74
33 0x22ff74
为什么同一地址有两个不同的值?
我无法理解为什么在下面的代码片段引用及其相关变量给出不同的结果.
const int x = 10;
const int &ptr = x;
int& y = const_cast<int&>(ptr);
y = 19;
std::cout << "x = " << x << " ptr=" << ptr << " y=" << y << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出:
x=10 ptr=19 y=19
Run Code Online (Sandbox Code Playgroud)
按我的理解,引用只是变量别名,为什么ptr是19和x是10?这是事做const还是const_cast?
我的问题是,为什么第一部分代码在第二部分工作时不起作用.非const指针应该先使用const_cast修改const值,但是使用整数这个技巧不起作用.你能解释一下为什么会这样吗?
const int i = 5;
cout << i << endl; //output: 5
int *ptr_i = const_cast<int*>(&i);
*ptr_i = 100;
cout << i << endl; //output : 5
const double d = 5;
cout << d << endl; //output : 5
double *ptr_d = const_cast<double*>(&d);
*ptr_d = 100.;
cout << d << endl; //output : 100
Run Code Online (Sandbox Code Playgroud) 在C++中,可以const &改变的价值吗?
好吧,当然不能改变,可以吗?这const意味着什么.而且,听听Stroustrup:
甲
const左值参考指的是恒定的,这是从视角的参照的用户的点不可变的.
但是这个怎么样?
#include <iostream>
int main() {
int a = 0;
const int& r = a;
const int old_r = r;
++a;
const int new_r = r;
std::cout
<< "old_r == " << old_r
<< " but new_r == " << new_r << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的机器上,这输出,old_r == 0 but new_r == 1.
这是我真正的问题.在上面的代码中,查看该行
const int new_r = r;
Run Code Online (Sandbox Code Playgroud)
只要
&new_r既不在此行也不在代码的其他地方提取volatile,没有任何东西阻止优化编译器从合并old_r …
看看这个程序:
int main(){
const int a_const=10;
int * const a=const_cast<int * const>(&a_const);
*a=5;
}
Run Code Online (Sandbox Code Playgroud)
因此,地址a_const和指针 a具有相同的值.但改变a指向的价值,却没有a_const.