Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 265
quant_dev Avatar asked Jan 10 '16 00:01

quant_dev


2 Answers

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.

like image 69
alfC Avatar answered Sep 19 '22 01:09

alfC


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

like image 40
Victor Dyachenko Avatar answered Sep 18 '22 01:09

Victor Dyachenko