工会不会接受第 'string' 类成员

Union won't take members of type 'string'

本文关键字:string 成员 会不会      更新时间:2023-10-16

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

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;
   ^

你能解释一下,为什么吗?

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;

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