How to force std :: sort to use the move and move-assign constructor?

I have a class Data , which (as of now) is not copied. std::sort on std::vector<Data> works because I defined move-constructor and move-assign for Data . I do it this way because the class has a lot of data inside and copying the content will be too slow. However, I am considering adding Data(const Data& other) and a standard assignment operator (from const Data& ) to the constructor class for unrelated reasons. How can I make sure that when sorting the Data vector, std::sort will still use the move and move-assign constructor?

+6
source share
2 answers

How can I make sure that when I sort the data vector, std :: sort will still use the move and move-assign constructor?

Actually, you do not need. You must make sure that the swap function used directly or indirectly uses any trick already used in the move constructor. This I think how it works. In other words, sort needs a good swap, not necessarily a copy.

Where "directly" may simply mean using the default std::swap , which uses the move constructor when possible.

 template <class T> void swap (T& a, T& b) { T c(std::move(a)); a=std::move(b); b=std::move(c); } 

So, most likely, you do not need to do anything, because swap (or, as @MarcGlisse noted, the sorting algorithm directly) will use the move constructor.

+1
source

Just enter move-constructor, move-assign and free swap function (in the same namespace) for your Data class

+2
source

All Articles