问题
Say I have some object declared as const volatile
:
According to the C++ standard ($7.1.5.1/8):
[..] 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.[...]
However, the const
qualifier implies than the object is not subject to change, so the two qualifiers appear to conflict:
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.
So, why are variables allowed be be const volatile
in the first place?
回答1:
If you define
const some_type 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
.
If you define
const volatile some_type x = some_value;
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.
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.
回答2:
This doesn’t make much sense:
int const volatile x = 42;
You’re right, x
cannot be changed — drop volatile
. However, the following is different:
int x = 42;
int const volatile& y = x;
Now y
cannot be changed, but x
can, and its change propagates through to y
. This works regardless of volatile
, of course — but if the change to y
comes from a source that is unobservable to the C++ compiler, volatile
may become necessary. Of course in cases where volatile
makes sense, the pointer/reference wouldn’t just refer to any other variable but rather to a specific memory address that is mapped to the hardware or elsewhere.
来源:https://stackoverflow.com/questions/33684826/c-why-does-the-const-volatile-type-qualifier-exist