mercredi 11 mars 2015

C++11 move constructor for union-like class

Is there a better way to build a move constructor for a union-like class? If I were to have a union-like class like the class in the following code, is there a way to build the class or the move constructor that wouldn't require switch statement like the move constructor in the following code.



class S {
private:
enum {CHAR, INT, DOUBLE} type; // tag
// anonymous union
union {
char c;
int n;
double d;
};

public:
// Move constructor with switch statement
S(S &&src) : type(std::move(src.type)) {
switch(type) {
case CHAR:
this->c = src.c);
src.c = 0;
break;
case INT:
this->n = src.n;
src.n = 0;
break;
case DOUBLE:
this->d = src.d;
src.d = 0
break;
default:
break;
}
}
};

Aucun commentaire:

Enregistrer un commentaire