是否有任何 C++ 标准保证 STL 迭代器可以存储在 union 中?如果是,哪个标准?
例如:
union MyUnion {
std::vector<int>::iterator iter;
size_t size;
};
我问的原因是我正在移植其他人的代码,这些代码在 union 中存储 std::vector
和 std::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/