变量定义中的C ++易失性类型量词位置

时间:2016-05-26 17:55:35

标签: c++ optimization volatile

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

  • volatile int * ptr;

指向的整数是volatile,当读/写此内存位置时,总是转到内存位置。

  • int * volatile ptr;

指针值本身为volatile,当读/写此内存位置时,总是转到内存位置。

这是一个微妙的区别,但从我所能说的不同之处就是这样。

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 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.
 ------------------------

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

1 个答案:

答案 0 :(得分:2)

是的,修饰符关键字顺序是灵活的。它在类型的左侧或右侧执行相同的操作。 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;