[英]Does making a struct volatile make all its members volatile?
If I have:如果我有:
struct whatever {
int data;
};
volatile whatever test;
will test.data
be volatile too?
test.data
也会不稳定吗?
Another question can be asked (or simply another way to look at the original question):可以问另一个问题(或者只是另一种看待原始问题的方式):
const
make all its members const
?const
使其所有成员都为const
吗? If I have:如果我有:
struct whatever { int data; };
const whatever test;
Will test.data be const
too? test.data 也会是
const
吗?
My answer is : Yes.我的回答是:是的。 If you declare an object of type
whatever
with const
then all its members will be const
too如果你用
const
声明一个whatever
类型的对象,那么它的所有成员也将是const
Similarly, if you declare an object of type whatever
with volatile
then all its members will be volatile
too, just like if you declare the object with const
, all it's member will be const
too.类似地,如果你用
volatile
声明一个whatever
类型的对象,那么它的所有成员也将是volatile
,就像你用const
声明对象一样,它的所有成员也将是const
。
const
and volatile
are two faces of the same coin; const
和volatile
是同一枚硬币的两个面; they're so that the Standard often refers to them as cv-qualifiers
.它们是这样的,标准经常将它们称为
cv-qualifiers
。
Quoting from the Standard ($7.1.5.1/8)引用标准 ($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.
[注意: volatile 是实现的提示,以避免涉及对象的激进优化,因为对象的值可能会通过实现无法检测的方式更改。 See 1.9 for detailed semantics.
有关详细语义,请参见 1.9。 In general, the semantics of volatile are intended to be the same in C + + as they are in C. ]
通常,volatile 的语义在 C++ 中与在 C 中的语义相同。]
That means, if your object is an instance of a struct, then the compiler cannot avoid aggressive optimization involving the object , unless it avoids aggressive optimization of each of it's members.这意味着,如果您的对象是一个结构体的实例,那么编译器将无法避免涉及 object 的主动优化,除非它避免对其每个成员进行主动优化。 (Otherwise, how else it can avoid optimization involving the object?)
(否则,它还能如何避免涉及对象的优化?)
Related topic:相关主题:
Why do we use volatile keyword in C++? 为什么我们在 C++ 中使用 volatile 关键字?
From: http://msdn.microsoft.com/en-us/library/145yc477%28v=vs.80%29.aspx来自: http : //msdn.microsoft.com/en-us/library/145yc477%28v=vs.80%29.aspx
To declare the object pointed to by the pointer as const or volatile, use a declaration of the form:要将指针指向的对象声明为 const 或 volatile,请使用以下形式的声明:
const char *cpch;
volatile char *vpch;
To declare the value of the pointer — that is, the actual address stored in the pointer — as const or volatile, use a declaration of the form:要将指针的值(即存储在指针中的实际地址)声明为 const 或 volatile,请使用以下形式的声明:
char * const pchc;
char * volatile pchv;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.