Samer Tufail
Samer Tufail

Reputation: 1894

C++ unions with string types

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?

Upvotes: 1

Views: 1773

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385335

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.

Upvotes: 2

Related Questions