17

If I have an object that only allows move-only semantics - is it possible to move items from a set? I can't seem to find a way to do this.

sircodesalot
  • 11,231
  • 8
  • 50
  • 83

2 Answers2

19

C++17 added a function std::set<>::extract that allows moving an object out of a set:

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
M.M
  • 138,810
  • 21
  • 208
  • 365
Irfy
  • 9,323
  • 1
  • 45
  • 67
15

No, it is not possible. There is no way to get non-const access to elements in a set, and move requires non-const references. Allowing non-const access would make it trivially easy to break the invariants for set.

Nevin
  • 4,595
  • 18
  • 24