C++ 从 const int* 到 int* 的转换会产生意想不到的结果 [英] C++ Conversion from const int* to int* working with unexpected results

查看:101
本文介绍了C++ 从 const int* 到 int* 的转换会产生意想不到的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,我们知道不能将 const int* 转换为 int*.但是我有一个代码片段,可以将 const int* 转换为 int*.我是 C++ 的初学者,我用谷歌搜索了这个,但我刚刚得到了提到 const int* 无法转换为 int* 以避免违反 const 的链接.我不知道为什么编译没有错误

In c++, we know that we can't convert const int* into int*. But I have a code snippet where I am able to convert const int* into int*. I am a beginner in c++, i googled for this but i just got the links mentioning const int* can't be converted into int* to avoid const violation. I am not able to figure out why is it compiling without errors

#include <iostream>
using namespace std;

int main(void)
{
    const int a1 = 40;
    const int* b1 = &a1;
    int* c1 = (int *)(b1);
    *c1 = 43;
    cout<< c1<<" "<< &a1<<endl;
    cout<< *c1<<" "<< a1<<endl;
 }

另外,问题是上面程序的输出是:

Also, the problem is the output of the above program is:

0x7fff5476db8c 0x7fff5476db8c
43 40

谁能解释一下 c1 整数指针指向 a1 的相同地址,但分别具有不同的值 43 和 40.

Can someone please explain c1 integer pointer is pointing to the same address for a1 but having different values 43 and 40 respectively.

推荐答案

在 C++ 中,一个对象要么是常量要么不是.如果它是 const 而不是任何修改它的尝试都会调用未定义的行为.这就是你所做的.那时任何事情都可能发生.如果幸运的话,它会崩溃.如果你不那么幸运,它可以正常工作,直到你的代码在客户手中,它会造成最大的损害.

In C++, an object is const or it isn't. If it is const than any attempt to modify it will invoke undefined behaviour. That's what you did. At that point anything can happen. If you're lucky, it crashes. If you're less lucky, it works fine until your code is in the hand of a customer where it causes the greatest possible damage.

您可以在 C++ 中轻松地将 const int* 转换为 int*.你刚刚做到了.但是,const int*"和int*"并不意味着所指向的东西是const 与否.这只是意味着编译器不会让你在一种情况下赋值,而会让你在另一种情况下赋值.*c1const.将指针投射到 int* 不会改变它是 const 的事实.未定义的行为.

You can easily convert a const int* to an int* in C++. You just did. However, "const int*" and "int*" don't mean that the thing pointed to is const or not. It just means that the compiler won't let you assign in one case, and will let you assign in the other case. *c1 is const. Casting the pointer to int* doesn't change the fact that it is const. Undefined behaviour.

这篇关于C++ 从 const int* 到 int* 的转换会产生意想不到的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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