Can I insert
to the moved container like this:
std::unordered_set<int> foo, bar;
bar = std::move(foo);
foo.clear(); // Should I do this?
foo.insert(0);
Can I insert
to the moved container like this:
std::unordered_set<int> foo, bar;
bar = std::move(foo);
foo.clear(); // Should I do this?
foo.insert(0);
A moved-from object should no longer be used.
If you insist, you will find that clear()
will actually leave you with an empty container, whether it was previously empty or not (which is not defined by the standard). Then when you insert, foo
will have one element in it.
A more normal way to write code like yours would be:
bar.swap(foo);
foo.clear();
foo.insert(0);
First of all, you can always insert into a set. Be it moved from, cleared, filled with elements etc., because insert has no preconditions (different from than e.g. erase).
But: If you don't call clear
after the move, you don't know if the newly inserted element will be the only element in the set
, because after the move, foo
is in a valid but unspecified state. So, not only can you call clear
after the move and befor inserting new elements, in most situations you should (unless you don't care what other elements are in the set).