引用已删除的析构函数 [英] Referencing deleted destructor
问题描述
我有以下代码:
struct Foo
{
int type;
union
{
int intValue;
double doubleValue;
std::wstring stringValue;
} value;
};
,然后在cpp文件中,我有:
and then in the cpp file I have:
std::vector<Foo> row;
some_class_object->func( row );
然后我得到了
error C2280: 'void *Foo::__delDtor(unsigned int)': attempting to reference a deleted function
这是什么问题?
所以我添加了这个析构函数:
So I added this destructor:
~Foo()
{
if( type ==3 )
value.stringValue.~std::wstring();
}
我收到一个错误:
error C2061: syntax error: identifier 'wstring'.
在这种情况下,显然std :: string vs std :: wstring很重要...
Apparently std::string vs std::wstring matter in this case...
对此一无所知.
我现在得到:
error C2280: 'Foo::<unnamed-type-value>::~<unnamed-type-value>(void)': attempting to reference a deleted function
推荐答案
联合包含一个具有非平凡析构函数的成员( 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.
这篇关于引用已删除的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!