如何解决更改const_cast ptr / ref的值不会更改原始对象的值吗?
在更改const_cast ptr / ref对象值后,我发现了一个奇怪的问题,即地址相同,值不同。
#include <iostream>
using namespace std;
int main(void){
const auto i=123;
auto &ref2i=i; auto ptr2i=&i;
auto pp=const_cast<int*>(ptr2i); *pp=456;
cout<<&i<<" with value "<<i<<endl;
cout<<pp<<" with value "<<*pp<<endl;
cout<<ptr2i<<" with value "<<*ptr2i<<endl;
auto &rr=const_cast<int&>(ref2i); rr=789;
cout<<i<<endl;
cout<<ref2i<<endl;
cout<<rr<<endl;
}
到底是怎么回事?
https://paiza.io/projects/HyLGbHxD2khynpclDWJnvA?language=cpp
输出:
0x7ffc1b0e8b54 with value 123
0x7ffc1b0e8b54 with value 456
0x7ffc1b0e8b54 with value 456
123
789
789
解决方法
如果您拼写出ptr2i
的类型,则会得到:
const int * ptr2i = &i; // since i is const
现在您可以const_cast
将此const int *
更改为int *
:
auto pp = const_cast<int*>(ptr2i); // ok
但是指向变量i
的类型为const int
,因此,如果您尝试修改指向变量的值,则:
*pp = 456; // oops,UB since you are attempting to modify i
您调用未定义的行为。这可能会导致程序执行任何操作,包括在同一地址显示不同的值。
当您将const int &
投射到int &
并尝试对其进行修改时,存在相同的限制。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。