是否可以从std::集中移出一个项目

Is it possible to move an item out of a std::set?

本文关键字:项目 一个 集中 std 是否 移出      更新时间:2023-10-16

如果我有一个只允许只移动语义的对象,那么可以从集合中移动项吗?我似乎找不到做这件事的方法。

C++17添加了一个函数std::set<>::extract,该函数允许将对象从集合中移出:

std::set<MoveOnlyType> s;
s.emplace(arg0, arg1, arg2); // only way to insert such move-only objects, since C++11
auto internal_node = s.extract(s.begin()); // internal_node no longer part of set, we can do with it what we want
MoveOnlyType m = std::move(internal_node.value()); // finally get the actual object out

不,这是不可能的。无法获得对set中元素的非常量访问,并且move需要非常量引用。允许非常量访问将使打破set的不变量变得非常容易。