1

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.

SwiftMango
  • 15,092
  • 13
  • 71
  • 136

3 Answers3

4

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • But in the example from the link, they did not use this swap for copy constructor.. why? – SwiftMango Nov 09 '13 at 19:52
  • @texasbruce: Constructors are different. If an exception is thrown midway through a constructor, the partially-constructed object will automatically be correctly destroyed before the exception propagates up the call stack. – NPE Nov 09 '13 at 19:54
1

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

Foo& operator= (Foo other) { 
  std::swap(data, other.data); 
  return *this;
}
  • @texasbruce The copy elision or move would be in the construction of 'other' –  Nov 09 '13 at 19:45
  • I see.. when you pass the parameter right? Its quite clever, but why not many people using this method? – SwiftMango Nov 09 '13 at 19:55
0

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?

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331