C ++ 11 move constructor for a unified class

Is there a better way to build a move constructor for a join type? If I had a class like union, such as the one in the following code, is there a way to build a class or move constructor that would not require a switch statement, such as 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: // constructor if the union were to hold a character AS(const char c) { this->tag = AS::CHAR; this->c = c; } // constructor if the union were to hold a int AS(const int i) { this->tag = AS::INT; this->n = i; } // constructor if the union were to hold a double AS(const double d) { this->tag = AS::DOUBLE; this->d = d; } // 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; } } }; 
+5
source share
1 answer

Since unions as a data type refer to the same memory location for all fields inside (although the order of smaller fields, such as 4 bytes of char [4] in this space, depends on the system), you can simply move the union using the largest field . This ensures that you move the entire union every time, regardless of the fields in which you are currently using the union.

 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)) { this->d = src.d; src.d = 0; } }; 
+2
source

Source: https://habr.com/ru/post/1215194/


All Articles