如何使用列表unique_ptr的C++ unordered_map

How to use C++ unordered_map of unique_ptr of list

本文关键字:C++ unordered map ptr 列表 unique 何使用      更新时间:2023-10-16
#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是临时的,因此它将被移出(自动,因为在这种情况下是可能的(。