Sometimes classes are referencing other classes. Implementing std::swap()
for such classes cannot be straightforward, because it would lead to swapping of original instances instead of references. The code below illustrates this behavior:
#include <iostream>
class A
{
int& r_;
public:
A(int& v) : r_(v) {}
void swap(A& a)
{
std::swap(r_, a.r_);
}
};
void test()
{
int x = 10;
int y = 20;
A a(x), b(y);
a.swap(b);
std::cout << "x=" << x << "\n"
<< "y=" << y << "\n";
}
int main()
{
test();
return 0;
}
A simple workaround with a union:
class A
{
union
{
int& r_;
size_t t_;
};
public:
A(int& v) : r_(v) {}
void swap(A& a)
{
std::swap(t_, a.t_);
}
};
This is effective, but not handsome. Is there a nicer way to swap two references in C++? Also how does C++ standard explain mixing references and values in one union, considering that in Stroustrup's "The C++ Programming Language" book a 'reference' is defined as an 'alternative name of an object, an alias' (p.189).