Context:
我正在努力学习智能指针,我遇到了一个我不明白的案例 .
我正在创建一个 unordered_map
的 unique_ptr<list<int>>
. 声明如下:
unique_ptr<unordered_map<uint32_t, unique_ptr<list<uint32_t>>>> mymap;
Map 及其内容是类的私有数据,我希望它们在类被销毁时被销毁 . 因此,我使用 unique_ptr
作为 Map 和每个列表 .
Problem:
当我打电话给 emplace
时,如下:
mymap->emplace(index, make_unique<list<uint32_t>>());
我的程序编译得很好 . 当我明确调用insert创建对时,它也有效:
mymap->insert(std::make_pair(index, std::make_unique<std::list<uint32_t>>()));
但是,以下行:
mymap->insert({index, make_unique<std::list<uint32_t>>()});
产生以下错误(Linux Ubuntu中的GCC)):
/ usr / include / c /5/ext/new_allocator.h:120:4:错误:使用已删除的函数'constexpr std :: pair <_T1,_T2> :: pair(const std :: pair <T1,T2 >&)[with _T1 = const unsigned int; _T2 = std :: unique_ptr>]'{:: new((void *) p)Up(std :: forward <Args>( args)...); }
从this answer我了解到,两种方法之间的区别在于 insert
将键值对复制或移动到容器中,而 emplace
将其构建到位 . 所以也许问题是我没有正确使用 unique_ptr
?
Question: Why the first two calls succeed while the third fails?