Reputation: 177
I would like to copy, in both directions, between volatile and non-volatile instances of a class. The following uses the assignment operator for the copy. If the macro "ordinary_cpp" is defined everything compiles as expected. If the macro is not defined, which enables "volatile", it copies a non-volatile to a volatile, but errors on the opposite, and always errors on the return of *this.
I hope someone can tell me the correct syntax to return *this, and how I can assign a volatile to a non-volatile. Thanks.
#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;)
}
Upvotes: 1
Views: 878
Reputation: 63039
You need 4 overloads, for
nonvol = nonvol;
nonvol = vol;
vol = nonvol;
vol = vol;
It would be something like
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;
}
};
But don't bother. volatile
is pretty vestigial at this point, and it definitely doesn't mean "safe to use with threads".
Upvotes: 4