是专门的std :: swap现在已经弃用了,我们有移动语义? [英] Is specializing std::swap deprecated now that we have move semantics?

查看:269
本文介绍了是专门的std :: swap现在已经弃用了,我们有移动语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

移动语义==自定义交换函数已过时


这是 std :: swap 如何在C ++ 11中:

  template< typename T> 
void swap(T& x,T& y)
{
T z = std :: move(x);
x = std :: move(y);
y = std :: move(z);
}

我还需要专门化 std :: swap 为我自己的类型,或将 std :: swap 与它获得的效率,只要我的类定义一个移动构造函数和移动分配 std :: swap

现在是可选的,但不会弃用。基本原理是性能。



对于原型代码,甚至是很多运输代码, std :: swap 快速。但是,如果你遇到需要从代码中查找每一点的情况,编写自定义交换仍然是一个显着的性能优势。



考虑case你的类基本上有一个拥有指针,你的移动构造函数和移动分配只需要处理一个指针。计算每个成员的机器负载和商店:



移动构造函数:1个加载和2个商店。



:2个加载和2个商店。



自定义交换:2个加载和2个商店。



std :: swap 是1个移动建筑和2个移动作业,或:5个加载项和6个商店。



自定义交换是潜在的仍然比 std :: swap 快两三倍。虽然任何时候你试图通过计数负载和商店来计算某事物的速度,两者都将是快速的。



注意:在计算成本您的移动分配,请确保并考虑到您将移动到一个移动的值(在 std :: swap 算法)。这通常会取消重新分配的成本,但代价是分支机构。


Possible Duplicate:
Move semantics == custom swap function obsolete?

This is how std::swap looks like in C++11:

template<typename T>
void swap(T& x, T& y)
{
  T z = std::move(x);
    x = std::move(y);
    y = std::move(z);
}

Do I still have to specialize std::swap for my own types, or will std::swap be as efficient as it gets, provided that my class defines a move constructor and a move assignment operator, of course?

解决方案

The specialization of std::swap is now optional, but not deprecated. The rationale is performance.

For prototyping code, and perhaps even for much shipping code, std::swap will be plenty fast. However if you're in a situation where you need to eek out every little bit from your code, writing a custom swap can still be a significant performance advantage.

Consider the case where your class essentially has one owning pointer and your move constructor and move assignment just have to deal with that one pointer. Count machine loads and stores for each member:

Move constructor: 1 load and 2 stores.

Move assignment: 2 loads and 2 stores.

Custom swap: 2 loads and 2 stores.

std::swap is 1 move construction and 2 move assignments, or: 5 loads and 6 stores.

A custom swap is potentially still two or three times faster than std::swap. Though any time you're trying to figure out the speed of something by counting loads and stores, both are going to be wicked fast.

Note: In computing the cost of your move assignment, be sure and take into account that you will be moving into a moved-from value (in the std::swap algorithm). This often negates the cost of a deallocation, though at the cost of a branch.

这篇关于是专门的std :: swap现在已经弃用了,我们有移动语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆