C++ Union usage

You need a C++11 compliant compiler. Read about union-s.

In general, you need to explicitly call the destructor of the old union member, and then the constructor of the new union member. Actually, you'll better have tagged unions, with the actual union being anonymous and member of some class:

class TreeRecord;

class TreeRecord {
   bool hassinglechild;
   typedef std::shared_ptr<TreeRecord> singlechild_type;
   typedef std::vector<std::shared_ptr<TreeRecord>> children_type;
   union {
     singlechild_type child;  // when hassinglechild is true
     children_type children;  // when hassinglechild is false
   }
   TreeRecord() : hassinglechild(true), child(nullptr) {};
   void set_child(TreeRecord&ch) {
     if (!hassinglechild) {
       children.~children_type();
       hassinglechild = true;
       new (&child) singlechild_type(nullptr);
     };
     child = ch;
   }
   /// other constructors and destructors skipped
   /// more code needed, per rule of five
}

Notice that I am explicitly calling the destructor ~children_type() then I am using the placement new to explicitly call the constructor for child.

Don't forget to follow the rule of five. So you need more code above

See also boost::variant

BTW your code is suggesting that you distinguish the case when you have a child and the case when you have a one-element vector of children. Is that voluntary and meaningful?

PS. In some languages, notably Ocaml, tagged unions (a.k.a. sum types) are considerably easier to define and implement than in C++11.... See wikipage of algebraic data types.

Tags:

C++

Unions