gpt4 book ai didi

c++ - 如何使用list的unique_ptr的C++ unordered_map

转载 作者:行者123 更新时间:2023-12-02 10:21:54 25 4
gpt4 key购买 nike

#include <memory>
#include <list>
#include <unordered_map>
class ClsA {
};

typedef std::list<ClsA*> ClsAList;
typedef std::unordered_map< int, std::unique_ptr < ClsAList> > ClsAListMap;

ClsAListMap map;
void Insert(int id, ClsA *a) {
auto list = new ClsAList{ a };
std::unique_ptr<ClsAList> smart_list(list);

//compilation error here
map.insert(id, smart_list);//error
map.insert({ a, smart_list});//error
}

由于模板的级别多种多样,错误提示根本不可读,这怎么了?

顺便说一句,在这种情况下如何使用 make_unique?我尝试过没有成功,只有漫长的错误提示噩梦。

最佳答案

您需要修复两件事。第一个是要对新元素进行emplace(可以使用insert,但会涉及更多内容)。第二个是,由于您无法复制unique_ptr,因此需要移动它:

map.emplace(id, std::move(smart_list));

要使用 make_unique,您需要对列表进行一些初始化:
auto list = std::make_unique<ClsAList>(1, a);

这使用构造函数,该构造函数将初始数量的元素放入列表中并将其设置为值。

最后,这些可以合并为一个语句:
map.emplace(id, std::make_unique<ClsAList>(1, a));

由于初始 unique_ptr是临时的,因此它将被自动移出(自动,因为在这种情况下可能)。

关于c++ - 如何使用list的unique_ptr的C++ unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59797339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com