简体   繁体   English

如何强制std :: sort使用move构造函数和move-assignment?

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

I have a class Data which is (as for now) non-copyable. 我有一个Data类,目前(不可复制)。 std::sort on std::vector<Data> works because I have defined move-constructor and move-assignment for Data . std::sort std::vector<Data>上的std::sort有效,因为我为Data定义了move-constructor和move-assignment。 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. 但是,出于不相关的原因,我现在正在考虑将复制构造函数Data(const Data& other)和标准赋值运算符(来自const Data& )添加到类中。 How can I make sure that when I sort a vector of Data , std::sort will still use the move-constructor and move-assignment? 我怎样才能确保当我排序的矢量Datastd::sort仍然会使用移动构造函数和移动赋值?

How can I make sure that when I sort a vector of Data, std::sort will still use the move-constructor and move-assignment? 如何确定对向量的向量进行排序时,std :: sort仍将使用move-constructor和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. 您必须确保使用的swap函数直接或间接利用了move构造函数中已经使用的任何技巧。 That is I think how it works. 我认为这是如何运作的。 In other words, sort needs a good swap, not necessarily a copy. 换句话说, sort需要良好的交换,而不必是副本。

Where "directly" could mean simply using the default std::swap that uses the move constructor when it can. “直接”的意思是简单地使用默认的std::swap ,它会在可能时使用move构造函数。

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. 因此,很有可能,您不需要做任何特殊的事情,因为swap (或正如@MarcGlisse指出的那样,直接使用排序算法)将使用move构造函数。

只需为您的Data类提供move-constructor,move-assignment和free swap -function(在同一名称空间中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM