阅读cppreference.com's page on Unions,下面是一个示例:
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>))
boost::variant
的动机是在std::string
中包含union
是非法的,因此对SO问题why-compiler-doesnt-allow-stdstring-inside-union的答案也是如此。哪一个是对的?为什么cpp-reference中的代码起作用?
最佳答案
您应该阅读链接的[旧]问答中的所有答案,而不仅仅是一个。
kennytm's answer解释了该规则在C ++ 11中得到了放松,并给出了一个示例。