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

问题描述 投票:1回答:1
#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?我尝试过没有成功,只有漫长的错误提示噩梦。

c++ unique-ptr
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.