为什么在C ++中swap不使用Xor操作 [英] Why swap doesn't use Xor operation in C++

查看:148
本文介绍了为什么在C ++中swap不使用Xor操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到Xor操作可用于实现有效的交换功能。像这样:

I've learned that Xor operation can be used to implement effective swap function. like this:

template<class T>
void swap(T& a, T& b)
{
    a = a^b;
    b = a^b;
    a = a^b;
}

但是我在互联网上可以找到的所有swap的实现基本上都是这样的:

But the implementation of swap all i can found on the internet is essentially like this:

template<class T>
void swap(T& a, T& b)
{
    T temp(a);
    a = b;
    b = temp;
}

似乎编译器没有为两种形式生成相同的代码上面的内容是因为我在VC ++ 2010上进行了测试,并且第一个比 std :: swap 做得更快。第一个有便携式或其他任何问题吗?随意纠正我的任何错误,因为我不是英国人,也不擅长C ++。

It seems that the compiler didn't generate the same code for the two form above because I tested it on VC++ 2010 and the first one is done the job more quickly than std::swap. Is there portable or any other problem with first one? Feel free to correct any of my mistake cause i'm not an English native and not good at C++.

(编者注:很可能是在非优化的调试版本,而不是 std :: swap 可以内联的发行版本,对调试版本进行基准测试是没有意义的,编译器通常不会将xor交换优化为更有效的方法。 )

(Editor's note: likely that test was done with a non-optimized debug build, not a release build where std::swap could inline. Benchmarking debug builds is meaningless. Compilers generally don't optimize away xor-swap into something more efficient.)

推荐答案


我了解到Xor操作可用于实现有效的交换功能

I've learned that Xor operation can be used to implement effective swap function

恐怕您学习错了。 XOR交换已经过时:如果可靠地比使用临时值快,那​​么就不应该在现代编译器和处理器上使用(现代指的是大约20年或更长时间)。您说这对您来说更快,也许您应该显示基准代码,看看其他人是否也得到相同的结果。

You learned wrong, I'm afraid. XOR swap is outdated: if it was ever reliably faster than using a temporary value then it shouldn't be on modern compilers and processors (where by "modern" I mean roughly the last 20 years or more). You say it was faster for you, possibly you should show your benchmark code and see whether others get the same results.

除了您的代码根本无法工作之外在整数类型上,它有一个基本的错误。尝试使用您的swap版本:

Aside from the fact that your code only works at all on integer types, it has a fundamental bug. Try this with your version of swap:

int a = 1;
swap(a,a);
std::cout << a << '\n';

这篇关于为什么在C ++中swap不使用Xor操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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