Copy-and-Swap Idiom

Seen in CS247 - Software Engineering Principles

Example use Copy Assignment Operator

Node& Node::operator=(const Node& other) {
	Node tmp{other};
	std::swap(data, tmp.data);
	std::swap(next, tmp.next);
	return *this;
}

How does it work?

Conceptually, it works by using the copy-constructor’s functionality to create a local copy of the data, then takes the copied data with a swap function, swapping the old data with the new data. The temporary copy then destructs, taking the old data with it. We are left with a copy of the new data.

In order to use the copy-and-swap idiom, we need three things: a working copy-constructor, a working destructor (both are the basis of any wrapper, so should be complete anyway), and a swap function.

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!

Refer to: https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom!

Example