3

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

I knew that I had this problem when I started with C++: The compiler wouldn't allow me to put a variable of the type std::string into unions.

That was years ago, but actually I still don't know the exact answer. I read something related to a copy function with the string that the union didn't like, but that's pretty much all.

  • Why are C++ STL strings incompatible with unions?
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 3
    Have a look at this: http://stackoverflow.com/questions/3521914/why-compiler-doesnt-allow-stdstring-inside-union โ€“ Bart Jun 24 '11 at 21:55

2 Answers2

5

From 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.

Think about it this way: If you have a union of a class type like std::string and a primitive type (let's say a long), how would the compiler know when you are using the class type (in which case the constructor/destructor will need to be called) and when you are using the simple type? That's why full-fledged class types are not allowed as members of a union.

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
4

Class which have user-defined constructor or user-defined destructor is not allowed in union.

You can have pointer of such class as member of union, though.

struct X
{
   X() {}
   ~X() {}
};

union A
{
   X x; // not allowed - X has constructor (and destructor too)
   X *px; //allowed!
};

Or you can use boost::variant which is a safe, generic, stack-based discriminated union container.

ยง9.5/1 says (formatting and emphasize is mine)

  • A union can have member functions (including constructors and destructors), but not virtual (10.3) functions.
  • A union shall not have base classes.
  • A union shall not be used as a base class.
  • 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.
  • If a union contains a static data member, or a member of reference type, the program is ill-formed.

Interesting!

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Is this a definite workaround? This answer seems overlooked and I'd really like to know more. What are the disadvantages/worries/issues with using pointers in a union, if any? โ€“ skippr Oct 26 '13 at 16:51
  • @sunday: Yes. Or you can use `boost::variant`. โ€“ Nawaz Oct 26 '13 at 18:50