c++ - 在 union 中存储 STL 迭代器是否合法?

标签 c++ stl unions

是否有任何 C++ 标准保证 STL 迭代器可以存储在 union 中?如果是,哪个标准?

例如:

union MyUnion {
   std::vector<int>::iterator iter;
   size_t size;
};

我问的原因是我正在移植其他人的代码,这些代码在 union 中存储 std::vectorstd::map 迭代器,而 MSVC2013 没有好像不喜欢我收到错误 C2621:非法 union 成员; type ... 有一个复制构造函数。我想确定这是代码中的错误、MS STL 实现中的错误还是我的编译器中的错误。

非常感谢!

最佳答案

您的编译器已过时。来自C++03标准,

An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects.

但是,此限制已在 C++11 中删除。取而代之的是一条注释:

[ Note: If any non-static data member of a union has a non-trivial default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8), or destructor (12.4), the corresponding member function of the union must be user-provided or it will be implicitly deleted (8.4.3) for the union. — end note ]

所以它是说,当然,你可以把一些带有非平凡复制构造函数的东西放在一个 union 中,但是除非你自己为它编写一个复制构造函数,否则 union 将不可复制。

关于c++ - 在 union 中存储 STL 迭代器是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30417121/

相关文章:

c++11 - 将 std::promise 对象存储在 std::pair 中

c++ - 为什么 STL 数值算法使用 'op' 而不是 'op=' ?

c++ - 一个 union 内的不同匿名 union 之间具有相同名称的字段

c++ - 在一系列方程式上使用 boost::bisect

c++ - ifstream.fail() 在 open() 之后返回 true

c++ - 从字符串类型到类类型的隐式转换

c++11 - 在 C++11 中为 STL 容器分配一个支撑初始化列表

c++ - 错误 : illegal cast: from 'int' to 'union'

c - 使用字符数组作为长整型数组

c++ - C++中是否存在真正的静态多态性?