【发布时间】:2020-12-05 07:04:19
【问题描述】:
考虑以下几点:
#include <set>
#include <map>
struct MyClass
{
MyClass(int i);
MyClass(MyClass const&) = delete;
~MyClass();
bool operator<(const MyClass& r) const { return v < r.v; }
int v;
};
void map_set_move_test()
{
std::set<MyClass> s1, s2;
std::map<int, MyClass> m1;
s1.emplace(123);
s2.insert(std::move(s1.extract(s1.begin())));
// This fails
m1.insert(std::move(std::make_pair(1, std::move(s2.extract(s2.begin()).value()))));
}
我使用std::set::extract 成功地将一个元素从std::set 移动到另一个std::set,如下所示:
s2.insert(std::move(s1.extract(s1.begin())));
但编译器不允许以这种方式将元素移动到std::map:
m1.insert(std::move(std::make_pair(1, std::move(s2.extract(s2.begin()).value()))));
任何帮助将不胜感激。 Link to compiler explorer.
【问题讨论】:
-
请比“不能”更具体。
-
我不确定在不同容器类型之间传输实现定义的节点句柄是否是预期的用例?!
-
@lubgr 但是
value()可以得到节点句柄的实际值,如果我没记错的话? -
不能加移动构造函数吗?
-
写
std::move(std::make_pair(...));对我来说没有多大意义。
标签: c++ c++17 move-semantics stdmap stdset