使用已删除的函数 'std::pair、std::basic_string >
我正在使用 std::pair
和 make_pair()
使用这对字符串创建一个 std::map
。但我收到以下编译错误:
/opt/rh/devtoolset-7/root/usr/include/c++/7/ext/new_allocator.h:140:22: error: use of deleted function 'std::pair<const std::pair<std::basic_string<char>, std::basic_string<char> >, firmware_data>::~pair()'
destroy(_Up* __p) { __p->~_Up(); }
我所做的声明如下:
typedef std::pair<std::string, string> FirmwareKey_t;
typedef std::map<FirmwareKey_t, firmware_data_t> FirmwareDataMap_t;
其中 firmware_data_t
是一个结构对象,定义为:
typedef struct firmware_data {
string name;
value_t abc; // value_t is of union type
bool configurable;
update_status_t def; //update_status_t is of enum type
} firmware_data_t;
Union 声明:
typedef union value {
string string_val;
bool boolean_val;
int64_t int_val;
uint uint_val;
} value_t;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该错误表明
map
的value_type
(又名std::pair
)具有已删除的析构函数。为此,可以使用
map::key_type
或map::mapped_type
类型(在本例中为FirmwareKey_t
和firmware_data_t< /code> 分别)有一个已删除的析构函数。
FirmwareKey_t
显然不是这种情况,因此它必须是firmware_data_t
,其中包含union
的value_t
成员类型。 根据 cppreference:这意味着您的联合体中的一个字段是一种不平凡的类型,它定义了析构函数,因此联合体本身有一个已删除的析构函数,因此任何类型使用
union
作为数据成员的也有一个删除的析构函数,等等。事实上,
union
中的该字段是string string_val
字段。因此,您需要修复您的
union
。由于std::string
需要销毁,因此您需要为union
显式定义一个析构函数来调用std::string
的析构函数,但是仅当string_val
是union
的活动字段时,例如:您还需要为您的
union
定义复制构造函数和复制赋值运算符, 也。话虽这么说,更好的解决方案是使用
std::variant
而不是联合
。std::variant
是一个类型安全的union
,可以自动为您处理这些详细信息。The error is saying that the
map
'svalue_type
(akastd::pair<const Key, T>
) has a deleted destructor.For that to happen, either the
map::key_type
ormap::mapped_type
type (in this case,FirmwareKey_t
andfirmware_data_t
, respectively) has a deleted destructor. That is clearly not the case forFirmwareKey_t
, so it must befirmware_data_t
, which contains avalue_t
member ofunion
type. According to cppreference:Which means one of the fields in your
union
is of a non-trivial type that has a destructor defined, and so theunion
itself has a deleted destructor, and thus any type that uses theunion
as a data member also has a deleted destructor, and so on.And, in fact, that field in your
union
is thestring string_val
field.So, you need to fix your
union
. Sincestd::string
requires destruction, you need to explicitly define a destructor for yourunion
to callstd::string
's destructor, but only whenstring_val
is the active field of theunion
, eg:You will also need to define a copy costructor and copy assignment operator for your
union
, too.That being said, a better solution is to use
std::variant
instead of aunion
.std::variant
is a type-safeunion
that handles these details automatically for you.