Search code examples
c++swapunions

proper way to swap unions?


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.


Solution

  • Simply:

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

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