2015-01-21 45 views
0

的成员。它有什么问题吗?:联盟不会采取型“串”

_foo.cpp:6:3: error: use of deleted function 'foo::foo()' 
} bar; 
^
_foo.cpp:4:7: note: 'foo::foo()' is implicitly deleted because the default definition would be ill-formed: 
union foo { 
    ^
_foo.cpp:5:14: error: union member 'foo::dunno' with non-trivial 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' 
    std::string dunno; 
      ^
_foo.cpp: In function 'void __static_initialization_and_destruction_0(int, int)': 
_foo.cpp:6:3: error: use of deleted function 'foo::~foo()' 
} bar; 
^
_foo.cpp:4:7: note: 'foo::~foo()' is implicitly deleted because the default definition would be ill-formed: 
union foo { 
    ^
_foo.cpp:5:14: error: union member 'foo::dunno' with non-trivial 'std::basic_string<_CharT, _Traits, _Alloc>::~basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' 
    std::string dunno; 
      ^
_foo.cpp: In function 'void __tcf_1()': 
_foo.cpp:6:3: error: use of deleted function 'foo::~foo()' 
} bar; 
^

你能解释一下,为什么?

回答

9

C++ 11确实引入了在工会中包含任意类型的可能性。但是,您需要向工会提供这些类型所有的特殊成员函数。它很好地总结了C++ 11 9.5/2:

[注:如果工会的任何非静态数据成员有一个不平凡的默认 构造函数(12.1),拷贝构造函数(12.8) ,移动构造函数(12.8),复制赋值运算符(12.8),移动 赋值运算符(12.8)或析构函数(12.4),联合的相应成员函数必须是用户提供的 或将被隐式删除(8.4。 3)为工会。 末端注]

这意味着,如果你希望你的工会有一个默认的构造函数,你必须定义它,像这样:

union foo { 
    std::string dunno; 
    foo() : dunno() {} 
} bar; 
0

C++ 03标准禁止使用的类型在union中使用的非平凡构造函数(std::string构造函数是非平凡的)。这个限制在C++ 11中被删除了。 此外,如果union具有非平凡构造函数的成员,您还需要定义构造函数。