const_cast<>的目的是什么?在波动?

时间:2010-06-12 22:43:46

标签: c++ casting standards volatile

我看到它可以做到,但我不明白它的兴趣。

3 个答案:

答案 0 :(得分:23)

这是安德烈·亚历山德里斯库(Andrei Alexandrescu)的一个Dr. Dobbs article,其中涉及的内容相当晦涩。

答案 1 :(得分:4)

constvolatile是正交的。

const表示数据是只读的。

volatile表示变量可能由于外部原因而发生变化,因此编译器每次引用时都需要从内存中读取变量。

因此删除const允许您编写其他只读位置(代码必须具有一些特殊知识,该位置实际上是可修改的)。您不应删除volatile来编写它,因为您可能会导致未定义的行为(由于7.1.5.1/7 - If an attempt is made to refer to an object defined with a volatile-qualified type through the use of an lvalue with a non-volatile-qualified type, the program behaviour is undefined.

答案 2 :(得分:3)

constvolatile听起来像是在变量上引用相同的想法,但它们没有。当前代码无法更改const变量。当前代码之外的某个外部实体可能会更改volatile变量。有可能有一个const volatile变量 - 尤其是类似于内存映射寄存器的变量 - 在程序无法预测的情况下被计算机更改,但不允许您的代码直接更改。您可以使用const_cast向变量添加或删除constvolatile(“cv-qualification”)。

相关问题