使用 C++11 无限制联合时的 VS 2013 异常

VS 2013 exception when using C++11 unrestricted unions

考虑这段代码:

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模式下没有问题。当 运行 处于调试模式时,xutility 中 class _Iterator_base12 的方法_Adopt 的最后一条语句出现异常:Access violation reading location 0x0000005C

在_Adopt 中代码只有运行 当_ITERATOR_DEBUG_LEVEL == 2。我试过

#define _ITERATOR_DEBUG_LEVEL 1

添加到我的主程序中,但它仍然定义为 2。 有没有办法禁用检查?

VS 2013 doesn't support C++11 unrestricted unions,即根据 C++03 实现联合:

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)时,您必须以安全的方式为联合实现构造函数、析构函数、复制构造函数等 constructs/destructs/copies 工会的适当部分。标准中有一个示例(我引用的是 C++14 草案 N4140 [class.union]/4):

Consider an object u of a union type U having non-static data members m of type M and n of type N. If M has a non-trivial destructor and N has a non-trivial constructor (for instance, if they declare or inherit virtual functions), the active member of u can be safely switched from m to n using the destructor and placement new operator as follows:

u.m.~M();
new (&u.n) N;