问题描述
我有一个类,它有一个联合作为其成员之一。我也是的忠实支持者。在我看来,似乎没有任何正确的(在标准的意义上)交换工会!
I have a class which has a union as one of its members. I also am a big fan of the copy/swap idiom. It occurred to me that there doesn't appear to be any correct (in the sense of the standard) to swap unions!
这里是最好的,我可以想出:
Here's the best that I could come up with:
char tmp[sizeof(U)];
memcpy(tmp, &u1, sizeof(U));
memcpy(&u1, &u2, sizeof(U));
memcpy(&u2, tmp, sizeof(U));
由于工会(至少在c ++ 03中)要求所有成员都是POD,看看为什么这不工作。但它只是不感觉正确。有更正确的方法来交换工会吗?
Since unions (at least in c++03) require that all members be POD, I don't see why this wouldn't work. But it just doesn't feel right. Is there a more correct way to swap unions? It seems almost like something that was overlooked.
好吧,看到提供的解决方案后,我觉得很蠢。我写下了传统的解决方案,例如 std :: swap
和赋值,因为当我第一次写代码时,联合是一个匿名联合。在当前版本的代码中,联合不再是匿名的,传统的解决方案似乎工作正常。感谢。
OK, I feel kinda dumb after seeing the solutions given :-). I wrote off traditional solutions like std::swap
and assignment because when I first wrote the code, the union was an anonymous union. In the current version of the code, the union is no longer anonymous and traditional solutions seem to work just fine. Thanks.
推荐答案
简单:
#include <algorithm>
std::swap(u1, u2);
联盟都是可复制构造和可分配的,因此没有问题。
Unions are both copy-constructible and assignable, so there is no problem.
这篇关于正确的方式交换工会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!