This is to avoid the inconsistent state or in more better word we would say to make exception safety.
You may also check this related Thread:- What is the copy-and-swap idiom?
As mentioned by GManNickG in the above thread:-
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!
Also check Why do some people use swap for move assignments?