联盟不会采取类型'字符串'

时间:2015-01-21 09:44:54

标签: 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:
 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;
   ^

你能解释一下,为什么?

2 个答案:

答案 0 :(得分:9)

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

  

[注意:如果联合的任何非静态数据成员具有非平凡的默认值   构造函数(12.1),复制构造函数(12.8),移动构造函数(12.8),复制赋值运算符(12.8),移动   赋值运算符(12.8)或析构函数(12.4),联合的相应成员函数必须是   用户提供或将隐式删除(8.4.3)联盟。 -end note ]

这意味着如果你希望你的联盟有一个默认的构造函数,你必须定义它,如下所示:

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

答案 1 :(得分:0)

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

相关问题