0

I recently wrote code (relevant SO answer, associated code) whose swap operation was intended to have different semantics than a combination of copy construction and copy assignment. That's where I recognized that std::sort doesn't always use std::swap or any swap function found through ADL.

For those who aren't familiar with this I put together a small example:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
namespace thing {
struct thing {
 int dummy;
 operator int (void) const {
  return dummy;
 }
 thing (int value) : dummy (value) {}
 thing (thing const & other) : dummy (other.dummy) {
  cout << "copy   " << this << " from " << &other << endl;
 }
 thing & operator=(thing const & other) {
  dummy = other.dummy;
  cout << "assign " << this << " from " << &other << endl;
 }
 void swap (thing & other) {
  // not called
 }
};

void swap (thing & lhs, thing & rhs) {
  // not called
}
}

int main() {
 vector<thing::thing> data  = {1, 21, 42};
 cout << "sorting now" << endl;
 sort (begin (data), end (data), greater<int>{});
 return 0;
}

Now the fact that std::sort isn't always using std::swap has been addressed multiple times here on SO:

My question is: Has there been any consideration, in terms of a proposal or discussion, to force std::sort (and similar standard library functions) to actually use std::swap?

To me it feels a bit ... under specified ... that for the correct behavior of my code it's swap operation has to have the same semantics as the combination of copy (move) construction and copy (move) assignment.

I'm well aware of the fact that the actual implementation (using a copy followed by multiple assignments) is far more effective than applying swap to any two elements for sorting.

Community
  • 1
  • 1
Daniel Jour
  • 15,896
  • 2
  • 36
  • 63

1 Answers1

1

Definitely. See issue LWG 226 and paper N1523

A major issue is exactly what to call. ::std::swap cannot be overloaded, and unqualified swap may not be the right function. In fact, the finance industry has always been a major user of C++, and for them swap might very well be a swap.

MSalters
  • 173,980
  • 10
  • 155
  • 350