2

Does any C++ standard guarantee that STL iterators can be stored in a union? If so, which standard?

For example:

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

The reason that I ask is that I'm porting someone else's code that stores std::vector and std::map iterators in unions, and MSVC2013 doesn't seem to like it. I'm getting error C2621: illegal union member; type ... has a copy constructor. I would like to determine whether this is a bug in the code, a bug in the MS STL implementation, or a bug in my compiler.

Many thanks!

Ross Bencina
  • 3,822
  • 1
  • 19
  • 33

2 Answers2

8

Your compiler is out of date. From the C++03 standard,

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.

However, this restriction has been removed in C++11. Instead there is a note:

[ 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 ]

So it's saying that, sure, you can put something with a non-trivial copy constructor inside a union, but then the union will not be copyable unless you write a copy constructor for it yourself.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
1

Thanks to Brian's answer I was able to research more about this topic.

The C++11 feature that is being used is called unrestricted unions. In case you're interested, here is the working group proposal.

According to this page at MSDN, MSVC 2013 and earlier do not support unrestricted unions.

Visual Studio 2014 CTP does support unrestricted unions.

Ross Bencina
  • 3,822
  • 1
  • 19
  • 33