更新时间:2021-08-12 22:35:42
联合包含一个具有非平凡析构函数的成员( std :: string
).这意味着联合不能拥有默认的析构函数(它不知道要调用哪个成员的析构函数).因此,您需要提供一个自定义析构函数.
The union contains a member (std::string
) with a non-trivial destructor. This means that the union can't have a defaulted destructor (it wouldn't know which member's destructor to call). So you need to provide a custom destructor.
在您的情况下,定义一个不执行任何操作的联合析构函数,然后在struct析构函数中进行工作:
In your case define a union destructor that does nothing and then do the work in the struct destructor:
struct Foo {
int type;
union U {
int intValue;
double doubleValue;
std::wstring stringValue;
~U() noexcept {}
} value;
~Foo()
{
using std::wstring;
if (type == 3)
value.stringValue.~wstring();
}
};
请注意,复制/移动构造函数/分配也需要这样做.
Please note that you need to do this for copy/move constructor/assignments as well.
在C ++ 17中,您有 std :: variant
,这是一个安全的联合.
In C++17 you have std::variant
which is a safe union.