const_cast和UB [英] const_cast and UB

查看:169
本文介绍了const_cast和UB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ 5.2.11 / 7 - [注意:根据对象的
类型,写操作
通过指针,lvalue或指针
可以产生
未定义的行为(7.1.5.1)。]

$5.2.11/7 - "[Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier68) may produce undefined behavior (7.1.5.1). ]"

本节的措辞(C ++ 03)对我来说是令人惊讶的。什么是惊喜是两件事。

The wordings of this section (C++03) are surprising to me. What is suprising are two things.

a)首先,使用'may'。为什么是可能?标准中的其他地方对于未定义的行为是非常确定的

a) Firstly, the use of 'may'. Why is it 'may'? Other places in the Standard are very definitive about the undefined behavior

b)为什么抛弃一个最初的const对象的const不直接未定义的行为。为什么要触发UB需要写入?

b) Why is that the casting away the constness of a originally const object not straight away 'undefined behavior'. Why is it that a write is required for UB to be triggered?

推荐答案


使用'可能'。为什么是
它'可能'?标准
中的其他地方对于
未定义的行为非常确定

a) Firstly, the use of 'may'. Why is it 'may'? Other places in the Standard are very definitive about the undefined behavior

不要太深入在这里使用这个词。关键是,在这种情况下,抛弃const const会导致未定义的行为。

Don't look too deeply into the use of the word may here. The point is, casting away constness in this case causes undefined behavior.

C ++标准经常使用may或might b
$ b

The C++ standard uses "may" or "might" often, as in:


1.3.12:当国际
标准省略任何$ b $的描述时,也可以预期未定义的行为 b行为的明确定义。

1.3.12: Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior.

强调我。基本上,标准使用可能一词,如允许

Emphasis mine. Basically, the standard uses the word "may" as in "is allowed to".


b)为什么要抛弃原来const对象的
constness
不会立即' undefined
behavior'。为什么要触发UB需要一个写入

b) Why is that the casting away the constness of a originally const object not straight away 'undefined behavior'. Why is it that a write is required for UB to be triggered?

写触发UB是因为const对象可以存储在某些平台上的只读存储器中。

A write triggers UB because it's possible that const objects can be stored in read-only memory on certain platforms.

这篇关于const_cast和UB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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