开发者

Why is 'volatile' parasitic in C++?

Consider the following code:

int main()                                                                      
{                                                                             
    int i;          开发者_运维知识库                                                            
    volatile int* p = &i;                                                       
    int *v = p;                                                                 
    return 0;                                                                   
}

This gives an error in g++:

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

My intention was that I want to make p volatile. However, once I've read the value of p, I don't care if accessing v is volatile. Why is it required that v be declared volatile?

This is hypothetical code of course. In a real situation you could imagine that p points to a memory location, but is modified externally and I want v to point to the location that p pointed to at the time of v = p, even if later p is externally modified. Therefore p is volatile, but v is not.

By the way I am interested in the behaviour both when this is considered C and C++, but in C this only generates a warning, not an error.


If you mean that the pointer should be volatile, rather than the object it points to, then declare it as

int* volatile p;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜