C ++为什么“常量易失”类型限定词存在吗? [英] C++ Why does the "const volatile" type qualifier exist?

查看:79
本文介绍了C ++为什么“常量易失”类型限定词存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一些声明为 const volatile 的对象:

Say I have some object declared as const volatile:

根据C ++标准($ 7.1.5.1 / 8):

According to the C++ standard ($7.1.5.1/8):


[..] volatile是实现的一种提示,以避免对对象优化>因为对象
的值可能会通过实现中无法检测的方式更改。[...]

但是, const 限定词暗示对象是 not 可以更改的对象,因此出现了两个限定词冲突:

However, the const qualifier implies than the object is not subject to change, so the two qualifiers appear to conflict:

一个暗示该对象应被更改,因为它可能会发生变化;另一个暗示该对象应被区别对待,因为它是 not 随时可能更改。

One implies the object should be treated differently because it is subject to change, and the other implies it should be treated differently because it is not subject to change.

那么,为什么首先允许变量是 const volatile

So, why are variables allowed be be const volatile in the first place?

推荐答案

如果定义

const some_type x = some_value;

这意味着您无法修改 x 。在没有 volatile 的情况下,编译器可以将 x 的引用替换为 some_value

that means you can't modify the value of x. In the absence of volatile, the compiler can replace a reference to x by some_value.

如果您定义

const volatile some_type x = some_value;

然后您仍然无法修改 x (至少不使用名称 x ),但是编译器无法再假定其值不能更改。任何对 x 值的引用实际上都必须从内存中加载它的值。

then you still can't modify x (at least not by using the name x), but the compiler can no longer assume that its value cannot change. Any reference to the value of x must actually load its value from memory; it can't assume that it will always retain its initial value.

例如,可能有一些特定于编译器的属性将 x 与某些设备。名称 x 提供对象的只读视图; volatile 禁止某些优化。

For example, there might be some compiler-specific attribute that associates x with some device. The name x provides a read-only view of the object; the volatile inhibits certain optimizations.

这篇关于C ++为什么“常量易失”类型限定词存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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