【发布时间】:2019-09-30 23:32:07
【问题描述】:
我看到这里有一个非常接近的问答:Iterating over a container of unique_ptr's 但是,当它涉及地图的迭代时,我看不到如何避免复制/分配 unique_ptr。
当我迭代映射时,例如,为了简单起见,使用 c++17,假设 x 是 Foo 的 int 类型的公共成员变量:
map<string, unique_ptr<Foo> > my_map;
for (auto const& [key, val] : my_map) {
val->x = 1;
}
我得到了错误:
constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const std::__cxx11::basic_string<char>; _T2 = std::unique_ptr<Foo>]’ is implicitly deleted because the default definition would be ill-formed:
我确实看到另一个帖子 (Cannot iterate over map whose elements hold a uniq_ptr) 这样做:
map<string, wrapper_struct > my_map;
其中 wrapper_struct 是一个内部带有 unique_ptr 的结构。我的问题是:有没有更简单的解决方案?
【问题讨论】:
标签: c++11 unique-ptr stdmap