22

考虑以下代码:

int main()                                                                      
{                                                                             
    int i;                                                                      
    volatile int* p = &i;                                                       
    int *v = p;                                                                 
    return 0;                                                                   
}

这给出了一个错误g++

$ g++ -o volatile volatile.cpp 
volatile.cpp: In function ‘int main()’:
volatile.cpp:6: error: invalid conversion from ‘volatile int*’ to ‘int*’

我的意图是我想让它变得p不稳定。但是,一旦我读取了 的值p,我就不关心访问v是否是易失性的。为什么需要v声明为 volatile?

这当然是假设的代码。在实际情况下,您可以想象它p指向一个内存位置,但在外部进行了修改,我想v指向当时指向的位置pv = p即使后来p被外部修改。因此p是易变的,但v不是。

顺便说一句,我对这被认为是 C 和 C++ 的行为感兴趣,但在 C 中这只会产生警告,而不是错误。

4

2 回答 2

36

如果您的意思是指针应该是易失的,而不是它指向的对象,那么将其声明为

int* volatile p;
于 2010-03-19T14:50:13.777 回答
14

In C++ the volatile keyword applies the same kinds of restriction on what you can do as const does. The Standard refers to this as 'cv-qualification' as in 'const/volatile qualification. Consts can only be used by consts, and in much the same way volatiles can only be used by volatiles.

Just as an aside, this can help you in writing multithreaded code. Not by virtue of employing some compiler magic that makes your variable suddenly atomic or anything like that, but by forcing you to only act on volatile data in a volatile way. See this Alexandrescu article for more info.

于 2010-03-19T14:52:12.600 回答