1

I was thinking about the swap() idiom.

If we have a valid copy constructor, why cant the compiler generate a "swap" function behind the scene, by swapping the "this" pointers?

I am probably looking at this too simplistically, but i'm wondering why it cant be done.

aCuria
  • 6,935
  • 14
  • 53
  • 89

2 Answers2

3

I suppose it could, but it doesn't. The default versions of the constructors and assignments just construct/assign member-by-member. If you already need to write your own copy constructor (which apparently is a warning sign and should only happen in rare cases), your class has something non-trivial going on, and that most likely won't do the right thing.

Also, if the copy-constructor has to be written by hand and isn't just copying of members, then chances are that the swap function is non-trivial, too, so you'd have to provide that manually as well.

In C++0x, you can use = default to make the compiler generate constructors automatically and assignment operators automatically, but those will just operate member-by-member and not use the copy+swap idiom.

For most classes, however, you should be using resource managing containers for your members, which themselves implement the all the correct functionality, and your class itself should be able to use the default copy/move constructors and assignments.

Edit. To put it another way: Copy/Move+Swap is an idiom that you may choose, but it isn't the default way to recursively build larger types from smaller ones. There is no automatically implied swap (here is a previous discussion on the matter) because it's left to the user's design choices which way round to implement copy, move and swap.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • The default assignment operator is generated automatically, even with a user-defined copy constructor (most likely doing the wrong thing). – UncleBens Jul 24 '11 at 11:07
3

You can't swap this pointers. That just doesn't even make sense. Even ignoring for a minute the fact that swapping a pointer will not swap the values, this is just one alias to the object and there are many more.

Puppy
  • 144,682
  • 38
  • 256
  • 465