我想在两个方向复制一个类的易失性和非易失性实例.下面对副本使用赋值运算符。如果定义了宏"ordinary_cpp“,一切都会按预期进行编译。如果未定义宏,从而启用“易失性”,则它会将非易失性复制到易失性,但相反的则会出现错误,并且在返回*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;)
}发布于 2020-03-12 18:44:56
你需要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"。
https://stackoverflow.com/questions/60660058
复制相似问题