考虑这段代码:
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
在 Release模式下没有问题。在 Debug模式下运行时,xutility 中类 _Iterator_base12 的方法 _Adopt 的最后一条语句出现异常:访问冲突读取位置 0x0000005C
。
在 _Adopt 中,代码仅在 _ITERATOR_DEBUG_LEVEL == 2
时运行。我试过
#define _ITERATOR_DEBUG_LEVEL 1
添加到我的主程序中,但它仍然定义为 2。 有没有办法禁用检查?
最佳答案
VS 2013 doesn't support C++11 unrestricted unions ,即它按照 C++03 实现 union :
An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union
您通过使用未命名结构成功地欺骗了编译器,但这并没有解决问题:对象是非平凡的,而 VS2013 不支持它。
当您切换到更多符合 C++11 的编译器(例如 VS 2015)时,您必须以安全构造/析构/适当复制的方式为 union 实现构造函数、析构函数、复制构造函数等联盟的一部分。标准中有一个示例(我引用的是 C++14 草案 N4140 [class.union]/4):
Consider an object
u
of a union typeU
having non-static data membersm
of typeM
andn
of typeN
. IfM
has a non-trivial destructor andN
has a non-trivial constructor (for instance, if they declare or inherit virtual functions), the active member ofu
can be safely switched fromm
ton
using the destructor and placement new operator as follows:u.m.~M(); new (&u.n) N;
关于c++ - 使用 C++11 无限制 union 时的 VS 2013 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31049885/