Re: Can 'qsort' have an advantage over 'std::sort'?
 
Greg Herlihy wrote:
So how does std::sort rearrange items in a container if not by copying
them? The answer is: by swapping them.
I thought that this might be the case, but (a) I can't find any
requirement in the standard that it do so and (b) the implementations I
have handy (STLPort and libstdc++) appear to require the copy
constructor and assignment operator, even though I provide a suitable
swap() overload.
Here's the test I ran:
   #include <algorithm>
   class foo {
      foo(const foo&);
      foo& operator=(const foo&);
      int mData;
   public:
      foo(int i = 0): mData(i) {}
      foo& operator=( int i ) { mData = i; return *this; }
      bool operator<( const foo& rhs ) const
         { return mData < rhs.mData; }
      friend void swap(foo& lhs, foo& rhs);
   };
   void swap( foo& lhs, foo& rhs )
   {
      std::swap( lhs.mData, rhs.mData );
   }
   int main()
   {
      foo af [3];
      af[0] = 3;
      af[1] = 2;
      af[2] = 1;
      std::sort( af, af + 3 );
   }
I checked stable_sort() as well, with the same result.
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]