I am trying to get my head around the new C++11 non-trivial unions in Visual Studio 2015. Please have a look at a simplified class I created (note that this code might not compile in its current form):
class Type
{
public:
Type() :
mKind(eObject),
mObject()
{
}
? // move constructor and operator= removed
Type(const Type& that) :
mKind(eObject),
mObject()
{
if ( that.mKind == eArray ) {
mKind = eArray;
mArray.mDimension = 1;
mArray.mType.reset(new Type()); // <-- here I get crashes due to uninitialized mType
}
else {
mObject.mName = that.eObject.mName;
}
}
enum Kind { eArray, eObject } mKind;
struct ArrayInfo {
std::unique_ptr<Type> mType;
int mDimension;
};
struct ObjectInfo {
String mName;
};
union {
ArrayInfo mArray;
ObjectInfo mObject;
};
}
I read that you may only initialize one member of the union (otherwise the constructor is ill formed). In this case I choose the mObject variable. Compiling works fine and well, but at runtime when I try to assign values to the mArray part I get crashes as it seems that it has not been initialized. I have looked through numerous resources about non-trivial unions and they always only have a std::string in there. Now I wonder how I can make this work. Do I need something like:
mObject.~String();
new (&mArray) ArrayInfo();
Thanks for the help.