c++ - 使用 C++11 无限制 union 时的 VS 2013 异常

标签 c++ c++11 visual-studio-2013 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模式下没有问题。在 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 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;

关于c++ - 使用 C++11 无限制 union 时的 VS 2013 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31049885/

相关文章:

c++ - 如何将 SQLite c 文件(合并)与 cpp 应用程序链接?

c++ - 模板类+虚函数=必须实现?

c++ - 表达式 SFINAE : how to select template version based on whether type contains a function with one or more arguments

c++ - 有没有办法在旧版 C/C++ 编译器中使用 C++ 11 线程对象

xaml - Visual Studio 2013 更新 3,设计器不会加载

c++ - 在 C++14 中将模板变量传递给模板函数

c++ - 如何从 Vista 和 Windows 7 上的应用程序启动屏幕键盘

c++ - gcc std::regex 与 -fpack-struct 段错误

c++ - 如何将 const uint8_t [] 转换为 std::string?

asp.net - 从 Visual Studio 2013 上的应用程序中删除 Application Insight