C++ 赋值运算符在 class 的易失性和非易失性实例之间进行复制

C++ assign operator to copy between volatile and non-volatile instances of a class

我想在 class 的易失性和非易失性实例之间双向复制。以下使用赋值运算符进行复制。如果定义了宏 "ordinary_cpp",一切都会按预期进行编译。如果宏没有定义,启用了"volatile",它会把一个non-volatile复制到一个volatile,但是相反会出错,并且总是在*this.

的return上出错

我希望有人能告诉我 return *this 的正确语法,以及如何将易失性分配给非易失性。谢谢

#define ordinary_cpp
#ifdef ordinary_cpp
  #define cv_qual
  #define thiserrormacro(arg) arg
  #define hopefulmacro(arg) arg
#else
  #define cv_qual volatile
  #define thiserrormacro(arg)
  #define hopefulmacro(arg)
#endif

struct Class {
  int data;
  Class operator = ( Class lhs ) cv_qual {
    data = lhs.data;
    thiserrormacro(return *this;)
  }
};

void test(){
  Class         nonvol;
  Class cv_qual vol;

  vol = nonvol;

  hopefulmacro(nonvol = vol;)
}

你需要 4 个重载,

nonvol = nonvol;
nonvol = vol;
vol = nonvol;
vol = vol;

会是这样的

struct Class {
  int data;
  Class& operator = ( const Class& lhs ) {
    data = lhs.data;
    return *this;
  }
  volatile Class& operator = ( const Class& lhs ) volatile {
    data = lhs.data;
    return *this;
  }
  Class& operator = ( const volatile Class& lhs ) {
    data = lhs.data;
    return *this;
  }
  volatile Class& operator = ( const volatile Class& lhs ) volatile  {
    data = lhs.data;
    return *this;
  }
};

不过别费心了。 volatile 在这一点上很不成熟,而且它绝对 意味着 "safe to use with threads"