C++ 联合赢了';t接受类型为'的成员;字符串';

C++ 联合赢了';t接受类型为'的成员;字符串';,c++,c++11,C++,C++11,每当我试图编译这段代码时: union foo { std::string dunno; } bar; 这给了我很多错误。怎么了 _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: u

每当我试图编译这段代码时:

union foo {
    std::string dunno;
} bar;
这给了我很多错误。怎么了

_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;
   ^
\u foo.cpp:6:3:错误:使用已删除的函数'foo::foo()'
}酒吧;
^
_foo.cpp:4:7:注意:“foo::foo()”被隐式删除,因为默认定义的格式不正确:
联富{
^
_foo.cpp:5:14:错误:联合成员'foo::dunno'带有非平凡的'std::basic_string::basic_string()[with _CharT=char;_Traits=std::char_Traits;_Alloc=std::allocator]'
std::字符串dunno;
^
_foo.cpp:在函数“void”\uuuu static\u initialization\u和\u destruction\u 0(int,int)”中:
_foo.cpp:6:3:错误:使用已删除的函数“foo::~foo()”
}酒吧;
^
_foo.cpp:4:7:注意:“foo::~foo()”被隐式删除,因为默认定义的格式可能不正确:
联富{
^
_foo.cpp:5:14:错误:联合成员“foo::dunno”带有非平凡的“std::basic_string::~basic_string()[with _CharT=char;_Traits=std::char_Traits;_Alloc=std::allocator]'
std::字符串dunno;
^
_foo.cpp:在函数“void\uu tcf\u 1()”中:
_foo.cpp:6:3:错误:使用已删除的函数“foo::~foo()”
}酒吧;
^

你能解释一下原因吗?

C++11确实引入了在联合中包含任意类型的可能性。但是,您需要为union提供这些类型具有的所有特殊成员函数。它在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;

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