Sometimes classes are referencing other classes. Implementing std::swap()
for such classes cannot be straightforward, because it would lead to swapping of origi
Essentially what you would like to do, if I understand your example, is to rebind references. This you cannot do in C++. You can either swap the values in the referred to objects, or you can use pointers.
The union trick you're using is about as non-portable as code gets. The standard places no requirements whatsoever on how compilers implement references. They can (and most probably do) use pointers under the hood, but this is never guaranteed. Not to mention the fact that sizeof(size_t)
and sizeof(T*)
aren't required to be equal anyway.
The best answer to your problem is: don't use reference members if you need an assignable/swappable class. Just use a pointer member instead. After all, references are non-reseatable by definition, yet by wanting the class swappable, you want something reseatable. And that's a pointer.
Your program using union
is not legal, as you assign the reference but swap the integer than intend to use the reference again. You can read about why, here: Accessing inactive union member and undefined behavior?
An easy solution here is to use pointers instead of references. Then everything will work smoothly, with no special code. If you really don't like this, perhaps you can use boost::optional<int&>
instead of plain references, but I would struggle to see how that'd be better.
You may use std::reference_wrapper
instead of direct reference (which you cannot swap
) or pointer (which may be nullptr
). Something like:
class A
{
std::reference_wrapper<int> r;
public:
A(int& v) : r(v) {}
void swap(A& rhs)
{
std::swap(r, rhs.r);
}
int& get() const { return r; }
};
Live example