There was an email thread between my colleagues Mike and Joe on this.
In C++, all 3 swap’s work. Only the 3rd one doesn’t incur a temporary object, but it doesn’t swap the original objects a and b, but rather the pointers pa and pb.

class CTest
{
public:
int a;
};

void swap(CTest& ra, CTest& rb)
{
CTest rc = ra;
ra = rb;
rb = rc;
}

void swap(CTest* ra, CTest* rb)
{
CTest rc;
rc = *ra;
*ra = *rb;
*rb = rc;
}

void swap(CTest** ra, CTest** rb)
{
CTest* rc = *ra;
*ra = *rb;
*rb = rc;
}

int main(int argc, char* argv[])
{
CTest a, b;
const CTest* pa = &a;
const CTest* pb = &b;
a.a = 1;
b.a = 2;
swap(a, b);
swap(&a, &b);
swap(&pa, &pb);
}

In Java, nothing works! You just can’t write a simple swap function in Java. You’d have to swap all members in the two objects explicitly (use reflection).

Advertisements