46
class MyClass
{
    int x, y;
    void foo() volatile {
        // do stuff with x
        // do stuff with y
    }   
};

我是否需要将所有成员变量都声明为自动x处理?yvolatilevolatile

我想确保编译器x不会用“stuff with”重新排序“stuff with ”。y

编辑:如果我将普通类型转换为volatile类型会发生什么?这会指示编译器不要重新排序对该位置的访问吗?我想在特殊情况下将普通变量传递给参数为 volatile 的函数。我必须确保编译器不会通过之前或之后的读写重新排序该调用。

4

4 回答 4

42

标记成员函数volatile就像标记它const;这意味着接收器对象被视为被声明为volatile T*. 因此,任何对xor的引用都y将被视为volatile成员函数中的读取。而且,一个volatile对象只能调用volatile成员函数。

也就是说,您可能想要标记xy volatile无论如何,如果您确实希望对它们的所有访问都被视为volatile.

于 2011-01-28T09:43:36.930 回答
10

不必显式声明成员变量..

从标准文档9.3.2.3

同样,在访问对象及其非静态数据成员时,易失性语义(7.1.6.1)适用于易失性成员函数。

于 2011-01-28T10:04:05.940 回答
8

以下代码:

#include <iostream>

class Bar
{
    public:

        void test();
};

class Foo
{
    public:

        void test() volatile { x.test(); }

    private:

        Bar x;
};

int main()
{
    Foo foo;

    foo.test();

    return 0;
}

使用 gcc 编译时引发错误:

main.cpp: In member function 'void Foo::test() volatile':
main.cpp:14:33: error: no matching function for call to 'Bar::test() volatile'
main.cpp:7:8: note: candidate is: void Bar::test() <near match>

而且由于volatile实例不能调用non-volatile方法,我们可以假设,是的,x并且yvolatile在方法中,即使MyClass没有声明的实例volatile

注意:如果需要,您可以使用 a 删除volatile限定符;const_cast<>但是要小心,因为const在某些情况下,这样做可能会导致未定义的行为。

于 2011-01-28T09:43:58.093 回答
3

所以使用原始示例:

class MyClass
{
    int x, y;
    void foo() volatile {
        // do stuff with x
        // do stuff with y
        // with no "non-volatile" optimization of the stuff done with x, y (or anything else)
    }   
    void foo() {
        // do stuff with x
        // do stuff with y
        // the stuff done with x, y (and anything else) may be optimized
    } 
};
于 2014-09-03T20:54:31.663 回答