C++ 可变类型量词在变量定义中的位置

C++ Volatile Type Quantifier Position In Variable Definition

我一直在做一些研究,但没有找到好的答案,我希望能得到更好的理解。 我知道如何使用 volatile,但对它在变量声明中的位置不同时的作用有疑问,例如

指向的整数是volatile并且当reading/writing到这个内存位置时总是去内存位置。

指针值本身是 volatile 并且当 reading/writing 到这个内存位置时总是去内存位置。

这是一个细微的差别,但据我所知,差别是这样的。

volatile int * foo;
int * volatile bar;
volatile int testInt = 5;
 ------------------------
|          0x020         | - 0x000 (foo), memory location 0x000 can be cached.
 ------------------------ 
|          0x020         | - 0x010 (bar), memory location 0x010 can't be cached.
 ------------------------
|           5            | - 0x020 (testInt)
 ------------------------

我的问题是,如果 volatile 量词不是指针类型怎么办?

volatile int foo = 5;
int volatile bar = 5;
 ------------------------
|            5           | - 0x000 (foo), memory location 0x000 can't be cached.
 ------------------------ 
|            5           | - 0x004 (bar), memory location 0x004 can't be cached.
 ------------------------

这两个声明对于非指针声明不是做同样的事情吗?

是的,修饰关键字顺序是灵活的。它在类型的左侧或右侧执行相同的操作。 const 也是如此。

我更喜欢修饰符 类型之后,因为它允许您从右到左阅读以获得简单的英语定义.

int volatile * foo; // "foo is a pointer to a volatile int"
int * volatile foo;  // "foo is a volatile pointer to an int"
int const * foo; // "foo is a pointer to a constant int"
int * const foo; // "foo is a constant pointer to an int"

所以我在

上自我标准化
int volatile foo;