工会不会接受第 'string' 类成员
Union won't take members of type 'string'
每当我尝试编译这段代码时:
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 中删除。此外,如果联合具有具有非平凡构造函数的成员,则需要定义构造函数。
相关文章:
- 反转没有循环的字符串,C++中只有 std::string 成员
- C++ 入门 12.1:我可以在类中使用静态向量成员实现 StrBlob<string> 吗?
- 使用<string>提升::序列化序列化具有 vector<unique_ptr> 成员的类
- 如何使用<string>初始值设定项列表初始化unordered_map<字符串、unordered_set>成员?
- C++ 错误:'std::string'没有成员
- 我应该如何处理:错误 C2039 "分配":不是 Visual Studio 2017 中"cl::string"的成员?
- 'struct std::string'没有名为'c_string'的成员
- 在结构的联合成员中使用std::string时,无法引用默认构造函数
- 如何将STD :: String的值复制到Char数组类型的结构成员
- 如何将 std::vector<std::string> 转换为 boost::spirit 中结构的成员?
- std::string::substr成员函数的复杂性是什么?
- 不要使用 "const char *" 作为类的成员,如果你真的是"std::string"
- 获取指向成员std::string::size的指针无法与libc++链接,但可以与libstdc++一起使用
- 工会不会接受第 'string' 类成员
- std::string 作为成员函数的参数的奇怪行为
- 使用 move std::string 的 .data() 成员不适用于小字符串?
- 如何创建静态常量成员 std::string 数组
- 当传入具有std::string成员的结构时,C++-gdb会给出意外的输出
- 结构体的std::string成员的EXC_BAD_ACCESS错误
- 为什么push_back会在上行对象的string成员中抛出一个char ?