volatile struct = struct not possible, why?

后端 未结 3 760
粉色の甜心
粉色の甜心 2021-01-01 13:26
struct FOO{
    int a;
    int b;
    int c;
};

volatile struct FOO foo;

int main(void)
{
    foo.a = 10;
    foo.b = 10;
    foo.c = 10;
    struct FOO test = foo         


        
3条回答
  •  时光说笑
    2021-01-01 13:40

    To give another approach to an answer, to address why this doesn't make sense, rather than just where the C++ standard says this is invalid:

    The whole point of volatile is that you have precise control over which variable gets accessed when. That means given volatile int i, j;, i = 1; j = 2; and j = 2; i = 1; do not do the same thing. The compiler cannot freely transform one into the other. The same applies to reads: given volatile int i, j; int x, y;, x = i; y = j; and y = j; x = i; do not do the same thing. The presence of volatile means the accesses must happen in exactly the order you specified.

    Now, in your example, what should struct FOO test = foo; do? You've never specified whether you want to first read foo.a, then foo.b, finally foo.c, or perhaps first read foo.c, then foo.b, finally foo.a, or perhaps some other order.

    You can, if you wish, do this:

    struct FOO test;
    test.a = foo.a;
    test.b = foo.b;
    test.c = foo.c;
    

    Here, you explicitly specify the order of the accesses to foo's fields, so you avoid the problem.

提交回复
热议问题