Can't assign an object to a volatile object

后端 未结 2 905
青春惊慌失措
青春惊慌失措 2020-12-16 15:28

I want to assign an object to volatile object in the same type, but failed to do so with compiler error. How to change the program to make it? Besides to make it to work, wh

相关标签:
2条回答
  • 2020-12-16 15:42

    You need to define an assignment operator function for A with the volatile qualifier.

    class A
    {
        public:
    
        volatile A& operator = (const A& a) volatile
        {
          // assignment implementation
        }
    };
    

    If you don't define an assignment operator for a class, C++ will create a default assignment operator of A& operator = (const A&);. But it won't create a default assignment operator with the volatile qualifier, so you need to explicitly define it.

    0 讨论(0)
  • 2020-12-16 15:53

    I have encounted the same question. For example:

    struct A { int i; }
    volatile A a;
    A b;
    a = b;   // C2678 here.
    

    I found this method to resolve it:

    const_cast<A &>(a) = b;
    
    0 讨论(0)
提交回复
热议问题