proper way to swap unions?

痞子三分冷 提交于 2019-12-12 16:54:40

问题


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));

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.

What do you guys think?

EDIT:

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.


回答1:


Simply:

#include <algorithm>
std::swap(u1, u2);

Unions are both copy-constructible and assignable, so there is no problem.




回答2:


Why not use classical swap solution?

U u1, u2;
// ...
U t = u1;
u1 = u2;
u2 = t;

This is expected to work since assignment of unions is valid.



来源:https://stackoverflow.com/questions/5652071/proper-way-to-swap-unions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!