SwiftMango
SwiftMango

Reputation: 15284

Why using swap to implement copy assignment?

In here: http://en.m.wikipedia.org/wiki/Rule_of_three_(C++_programming)

/** Copy Assignment Operator */ 
Foo& operator= (const Foo& other) { 
  Foo temporary (other); 
  std::swap (data, temporary.data); 
  return *this;
 }

In the example, it uses std::swap to swap the data with a temporary. Why would we create a temporary and swap? Isn't it faster to just copy? I saw this in other places too and got confused.

Upvotes: 1

Views: 274

Answers (3)

user2249683
user2249683

Reputation:

In addition, to enable copy elision and (c++11) move semantics:

Foo& operator= (Foo other) { 
  std::swap(data, other.data); 
  return *this;
}

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

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?

Upvotes: 0

NPE
NPE

Reputation: 500187

The swap trick is a fairly easy way to ensure exception safety.

If you do a field-by-field copy, and get exception in the middle, your object could end up in an inconsistent state (unless you take steps to address this, which could complicate things considerably).

With the swap-based implementation, if the Foo temporary (other) throws, your object remains unaltered from its original state.

Upvotes: 4

Related Questions