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.
Asked
Active
Viewed 3,711 times
17
-
1@cppguy The elements of a set are immutable, so swapping or moving shouldn't work. – juanchopanza Aug 26 '14 at 21:26
-
@juanchopanza [This seem to work?](http://ideone.com/Z97Eve) – Felix Glas Aug 26 '14 at 21:30
-
3That works because `std::string` can fallback to copy semantics. – sircodesalot Aug 26 '14 at 21:31
-
@juanchopanza Heh, I trust you :) – Felix Glas Aug 26 '14 at 21:45
-
@Snps Here's [a better example](http://ideone.com/e0hNIX). It shows that the move calls the copy constructor, because the iterator is a `const_iterator` so you cannot get a non-const reference from it. If you comment out the copy constructor, it doesn't compile. – juanchopanza Aug 26 '14 at 21:57
-
2C++17 can do this via `extract` and `merge` – Mark K Cowan Feb 02 '17 at 23:55
2 Answers
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
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