One case where there is a benefit to implement your own swap1 function is in an assignment operator to manage/transfer dynamically allocated memory, by using the copy and swap idiom.
If you have the following class:
#include <algorithm> // std::copy
#include <cstddef> // std::size_t
class MyArray{
public:
// (default) constructor
MyArray(std::size_t size = 0)
: mSize(size), mArray(mSize ? new int[mSize]() : 0)
{ }
// copy-constructor
MyArray(const MyArray& other)
: mSize(other.mSize), mArray(mSize ? new int[mSize] : 0),
{ std::copy(other.mArray, other.mArray + mSize, mArray); }
// destructor
~MyArray(){ delete [] mArray; }
private:
std::size_t mSize;
int* mArray;
};
1. To implement the assignment operator
instead of:
MyArray& operator=(const MyArray& other){
if (this != &other){
// get the new data ready before we replace the old
std::size_t newSize = other.mSize;
int* newArray = newSize ? new int[newSize]() : 0;
std::copy(other.mArray, other.mArray + newSize, newArray);
// replace the old data
delete [] mArray;
mSize = newSize;
mArray = newArray;
}
return *this;
}
you could do:
MyArray& operator=(MyArray other){
swap(*this, other);
return *this;
}
2. To swap the members of a class safely:
friend void swap(MyArray& first, MyArray& second){
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}
Note: insight in this answer borrowed from this.
1 A swap function is a non-throwing function that swaps two objects of a class, member for member. We might be tempted to use std::swap instead of providing our own, but this would be impossible; std::swap uses the copy-constructor and copy-assignment operator within its implementation, and we'd ultimately be trying to define the assignment operator in terms of itself!