c++ - 为什么 std::string 与 C union 不兼容?

标签 c++ string unions

<分区>

Possible Duplicate:
Why compiler doesn't allow std::string inside union ?

当我开始使用 C++ 时,我知道我遇到了这个问题:编译器不允许我将 std::string 类型的变量放入 union 中。

那是几年前的事了,但实际上我仍然不知道确切的答案。我读了一些与复制函数相关的内容,其中包含 union 不喜欢的字符串,但仅此而已。

  • 为什么 C++ STL 字符串与 union 不兼容?

最佳答案

来自 Wikipedia :

C++ does not allow for a data member to be any type that has a full fledged constructor/destructor and/or copy constructor, or a non-trivial copy assignment operator. In particular, it is impossible to have the standard C++ string as a member of a union.

这样想:如果你有一个像 std::string 这样的类类型和一个原始类型(比如 long)的 union ,怎么会编译器知道您何时使用类类型(在这种情况下需要调用构造函数/析构函数)以及何时使用简单类型?这就是为什么成熟的类类型不允许作为 union 的成员。

关于c++ - 为什么 std::string 与 C union 不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6474158/

相关文章:

iphone - 如何在sqlite表中使用substr作为逗号分隔值

java - 为负数添加 if else

struct - Rust:使用两个u8结构字段作为u16

C++ 是否在多个文件单元中链接相同的静态库会增加大小/膨胀?

c++ - 在 C++ 中使用 std::bind 和 std::function 时出错

迭代器中的 C++ 后增量运算符重载(使用 -Wall -Werror 编译)

c - union 和结构初始化

c++ - 将先前分配的指针值传递给循环

java - 从文本文件中逐行读取车辆并将这些车辆传递到 Java 的构造函数中

c - union 内的 union