考虑以下代码:
struct TNumeric {
bool Negative;
wstring Integral;
wstring Fraction;
};
union TValue {
// The unnamed structs are needed because otherwise the compiler does not accept it...
bool Bit;
struct{ TNumeric Numeric; };
struct{ wstring Text; };
};
TNumeric Numeric;
TNumeric &rNumeric{ Numeric };
rNumeric.Integral = L"";
rNumeric.Integral.push_back( L'X' ); //OK, no problem
TValue Value;
TValue &rValue{ Value };
rValue.Text = L"";
rValue.Text.push_back( L'X' ); //OK, no problem
rValue.Numeric.Integral = L"";
rValue.Numeric.Integral.push_back( L'X' ); // Exception
在发布模式下没有问题。在调试模式下运行时,xutility中的类_Iterator_base12的方法_Adopt中的最后一个语句有一个异常:Access violation reading location 0x0000005C
。
在_Adopt中,代码仅在_ITERATOR_DEBUG_LEVEL == 2
时运行。我试过
#define _ITERATOR_DEBUG_LEVEL 1
在我的主程序中添加,但仍然定义为2。 有没有办法禁用支票?
答案 0 :(得分:5)
VS 2013 doesn't support C++11 unrestricted unions,即根据C ++ 03实现联合:
一个对象 具有非平凡构造函数(12.1)的类,非平凡复制构造函数(12.8),非平凡析构函数 (12.4),或非平凡的复制转让操作员(13.5.3,12.8)不能成为工会的成员
您使用未命名的结构成功欺骗了编译器,但这并没有解决问题:对象不重要,VS2013不支持。
当您切换到更多符合C ++ 11的编译器(例如VS 2015)时,您必须以一种安全构造/破坏/复制适当的方式为联合实现构造函数,析构函数,复制构造函数等工会的一部分。标准中有一个例子(我引用的是C ++ 14草案N4140 [class.union] / 4):
考虑具有非静态数据的联合类型
u
的对象U
m
类型的成员M
和n
类型的N
。如果M
有一个非平凡的析构函数,N
有一个非平凡的构造函数 (例如,如果他们声明或继承虚函数),u
的活动成员可以安全地切换 从m
到n
使用析构函数和放置new运算符,如下所示:u.m.~M(); new (&u.n) N;