1

Reading cppreference.com's page on Unions, an example is presented as below:

union S
{
    std::string str;
    std::vector<int> vec;
    ~S() {} // needs to know which member is active, only possible in union-like class 
};          // the whole union occupies max(sizeof(string), sizeof(vector<int>))

The motivation for boost::variant presents that it is illegal to have a std::string in a union and so does the answer to an SO question why-compiler-doesnt-allow-stdstring-inside-union.

Which one is right? and why does the code in the cpp-reference work?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Samer Tufail
  • 1,835
  • 15
  • 25

1 Answers1

2

You should read all the answers on the [old] Q&A you linked, not just one.

kennytm's answer explains that the rule was relaxed in C++11, and gives an example.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055