如果我有:
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
。
const
和 volatile
是同一枚硬币的两个面;它们因此标准经常将它们称为 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. ]
这意味着,如果您的对象是一个结构的实例,那么编译器就无法避免涉及该对象的积极优化,除非它避免对每个对象进行积极优化成员。 (不然怎么避免涉及到对象的优化?)
相关话题:
关于c++ - 使 struct volatile 会使它的所有成员 volatile 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479597/