首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++分配操作符在类的易失性实例和非易失性实例之间进行复制。

C++分配操作符在类的易失性实例和非易失性实例之间进行复制。
EN

Stack Overflow用户
提问于 2020-03-12 18:37:09
回答 1查看 417关注 0票数 1

我想在两个方向复制一个类的易失性和非易失性实例.下面对副本使用赋值运算符。如果定义了宏"ordinary_cpp“,一切都会按预期进行编译。如果未定义宏,从而启用“易失性”,则它会将非易失性复制到易失性,但相反的则会出现错误,并且在返回*this时总是会出现错误。

我希望有人能告诉我正确的语法返回*这,以及我如何可以分配一个易失性的非易失性。谢谢。

代码语言:javascript
复制
#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;)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-12 18:44:56

你需要4个过载

代码语言:javascript
复制
nonvol = nonvol;
nonvol = vol;
vol = nonvol;
vol = vol;

就像

代码语言:javascript
复制
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"

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60660058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档