是否将指针转换为const指针并转换回未定义的原始类型? [英] Is casting a pointer to const pointer and cast back to the original type undefined?

查看:57
本文介绍了是否将指针转换为const指针并转换回未定义的原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道将const指针强制转换为非const类型可能是未定义的行为,但是如果该指针最初不是const怎么办?

I know casting a const pointer to non-const type might be undefined behavior, but what if the pointer is originally not const?

int i = 0;
int * pi = &i;
const int * const_pi = const_cast<const int*>(pi);
int * non_const_pi = const_cast<int*>(const_pi);
*non_const_pi = 0;
*non_const_pi = 1;
int j = *non_const_pi;

是否存在未定义的行为?如果有的话,它们在哪里发生?编译器是否可以假定 non_const_pi 是从const指针强制转换的,并且不执行任何修改?

Is there's any undefined behavior? If any, where do they happen? May the compiler assume that non_const_pi is casted from a const pointer and perform no modification?

推荐答案

我知道将const指针转换为非const类型可能是未定义的行为.

I know casting a const pointer to non-const type might be undefined behavior.

那是个误会.

常量广播指针永远不会导致未定义的行为.取消引用通过 const_cast -将 const 指针指向 const 对象而获得的非 const 指针不是如果原始对象以只读模式使用,则未定义行为.如果您尝试写入对象,则这是未定义的行为.

Const-casting pointers is never cause for undefined behavior. Dereferencing a non-const pointer obtained by way of const_cast-ing a const pointer to a const object is not undefined behavior either if the original object is used in read-only mode. It is undefined behavior if you try to write to the object.

int const i = 10;
int const* p1 = &i;
int* p2 = const_cast<int*>(p1);  // OK.
std::cout << *p2;                // Still OK.
*p2 = 20;                        // Not OK.

鉴于此,您的第二段代码完全可以.因为原始对象是非 const 对象,所以没有未定义的行为.

Given that, your second block of code is perfectly OK. There is no undefined behavior since the original object is a non-const object.

来自该标准,第5.2.11节,表达式/const cast :

指针 const_cast 的结果引用原始对象.

这篇关于是否将指针转换为const指针并转换回未定义的原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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