c++ - 使 struct volatile 会使它的所有成员 volatile 吗?

标签 c++

如果我有:

struct whatever {
int data;
};<br/>
volatile whatever test;
test.data 也会易变吗?

最佳答案

可以提出另一个问题(或者只是以另一种方式查看原始问题):

是否制作一个结构 const 使其所有成员 const

如果我有:

struct whatever { int data; };

const whatever test;

test.data 也会是 const 吗?

我的回答是:是的。如果你用 const 声明一个 whatever 类型的对象,那么它的所有成员也将是 const

同样,如果你用 volatile 声明一个 whatever 类型的对象,那么它的所有成员也将是 volatile,就像你声明带有 const 的对象,它的所有成员也将是 const

constvolatile 是同一枚硬币的两个面;它们因此标准经常将它们称为 cv-qualifiers


引用标准 ($7.1.5.1/8)

[Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C + + as they are in C. ]

这意味着,如果您的对象是一个结构的实例,那么编译器就无法避免涉及该对象的积极优化除非它避免对每个对象进行积极优化成员。 (不然怎么避免涉及到对象的优化?)


相关话题:

Why do we use volatile keyword in C++?

关于c++ - 使 struct volatile 会使它的所有成员 volatile 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479597/

相关文章:

c++ - 如何从文件中读取特征矩阵?

c++ - wchar_t 字符数组中的奇怪符号

c++ - 在全局变量的初始化/取消初始化中使用隐式加载的 DLL 中的函数

C++ 用指针帮助警告

c++ - 使用字符串流时如何停止 double 转换为科学计数法

c++ - 为特定的读写操作重载下标运算符

c# - 将字符串从 C++ 传递到 C#

c++ - 编写此指针函数代码的长格式是什么?

c++ - 为什么在此代码的末尾引发异常?

c++ - 在 unsigned char 数组中设置 unsigned short