引用已删除的析构函数
我有以下代码:
struct Foo
{
int type;
union
{
int intValue;
double doubleValue;
std::wstring stringValue;
} value;
};
然后在cpp文件中我有:
std::vector<Foo> row;
some_class_object->func( row );
我得到了:
error C2280: 'void *Foo::__delDtor(unsigned int)': attempting to reference a deleted function
这里有什么问题?
编辑:
所以我添加了这个析构函数:
~Foo()
{
if( type ==3 )
value.stringValue.~std::wstring();
}
我得到了一个错误:
error C2061: syntax error: identifier 'wstring'.
在这种情况下,显然 std::string 与 std::wstring 很重要......
不知道。
编辑2:
我现在得到:
error C2280: 'Foo::<unnamed-type-value>::~<unnamed-type-value>(void)': attempting to reference a deleted function
回答
联合包含一个成员 ( std::string) 和一个非平凡的析构函数。这意味着联合不能有默认的析构函数(它不知道要调用哪个成员的析构函数)。所以你需要提供一个自定义的析构函数。
在您的情况下,定义一个什么都不做的联合析构函数,然后在结构析构函数中完成工作:
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();
}
};
请注意,您也需要为复制/移动构造函数/赋值执行此操作。
在 C++17 中,std::variant这是一个安全联合。
- @Igor "*so how do I write it?*" - see [Is a Union Member's Destructor Called](https://stackoverflow.com/questions/40106941/)