【发布时间】:2019-10-07 11:18:45
【问题描述】:
我想假设getKeys() 函数从map 中获取不可复制的键:
class MyObj {
// ... complex, abstract class...
};
struct Comparator { bool operator()(std::unique_ptr<MyObj> const &a, std::unique_ptr<MyObj> const &b); };
std::vector<std::unique_ptr<MyObj>> getKeys(std::map<std::unique_ptr<MyObj>, int, Comparator> &&map) {
std::vector<std::unique_ptr<MyObj>> res;
for (auto &it : map) {
res.push_back(std::move(it.first));
}
return res;
}
但它不起作用,因为 it (.first) 中的密钥是 const。任何提示如何解决它?注意:在我们的环境中,我不允许使用 C++17 函数std::map::extract()。
使用const_cast 是否可以,因为map 无论如何都会被破坏?
res.push_back(std::move(const_cast<std::unique_ptr<MyObj> &>(it.first)));
我想避免克隆MyObj。
我知道为什么不能修改 std::map 容器的键,但是对于将在键修改后立即销毁的映射仍然不允许这样做吗?
【问题讨论】:
-
你能从
std::unique_ptr切换到std::shared_ptr吗? -
请看下面我如何解决这个问题的答案。