C++ volatile member functions

后端 未结 4 2052
礼貌的吻别
礼貌的吻别 2020-12-02 15:48
class MyClass
{
    int x, y;
    void foo() volatile {
        // do stuff with x
        // do stuff with y
    }   
};

Do I need to declare

4条回答
  •  既然无缘
    2020-12-02 16:08

    The following code:

    #include 
    
    class Bar
    {
        public:
    
            void test();
    };
    
    class Foo
    {
        public:
    
            void test() volatile { x.test(); }
    
        private:
    
            Bar x;
    };
    
    int main()
    {
        Foo foo;
    
        foo.test();
    
        return 0;
    }
    

    Raises an error upon compilation with 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() 
    

    And since a volatile instance can't call a non-volatile method, we can assume that, yes, x and y will be volatile in the method, even if the instance of MyClass is not declared volatile.

    Note: you can remove the volatile qualifier using a const_cast<> if you ever need to; however be careful because just like const doing so can lead to undefined behavior under some cases.

提交回复
热议问题