I have a class Data which is (as for now) non-copyable. std::sort on std::vector<Data> works because I have defined move-constructor and move-assignment for Data. I do it this way because the class has a lot of data inside and copying the contents would be too slow. However, I am considering now adding a copy constructor Data(const Data& other) and standard assignment operator (from const Data&) to the class, for unrelated reasons. How can I make sure that when I sort a vector of Data, std::sort will still use the move-constructor and move-assignment?
How can I make sure that when I sort a vector of Data, std::sort will still use the move-constructor and move-assignment?
Actually, you don't need to. You have to make sure that the swap function used exploits directly or indirectly any trick already used in the move constructor. That is I think how it works. In other words, sort needs a good swap, not necessarily a copy.
Where "directly" could mean simply using the default std::swap that uses the move constructor when it can.
template <class T> void swap (T& a, T& b)
{
T c(std::move(a)); a=std::move(b); b=std::move(c);
}
So, chances are, you don't need to do anything special because swap (or as @MarcGlisse noted, the sort algorithm directly) will use the move constructor.
Just provide move-constructor, move-assignment and free swap-function (in the same namespace) for your Data class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With