开发者

proper way to swap unions?

I have a class which has a union as one of its members. I also am a开发者_C百科 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.


Simply:

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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜