Criss
Criss

Reputation: 611

Ignoring overload of swap function

I overloaded swap function for my class as in this answer, but while sorting (std::sort) compiler is still using std::swap. I don't see any difference between my approach and the one stated in linked answer. Here's reproduction of my code:

#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>

struct B
{
struct A
{
    friend void swap(A & a, A & b)
    {
        std::swap(a.a, b.a);
        std::cout << "my swap\n";   
    }

    A(int _a) : a(_a) {}
    bool operator<(const A & other) { return a < other.a; }
    int a;
};
};

int main()
{
    std::vector<B::A> v{1, 2, 3, 5, 4};
    std::sort(std::begin(v), std::end(v));
}

Also executable example provided here.

Upvotes: 4

Views: 129

Answers (1)

Jodocus
Jodocus

Reputation: 7591

The standard doesn't state in its specification (§25.4.1.1 [alg.sort]) that std::sort actually is guaranteed to call swap, it only mentions that the type must fulfill certain concepts which I wouldn't interpret as a guarantee:

Requires: RandomAccessIterator shall satisfy the requirements of ValueSwappable (17.6.3.2). The type of *first shall satisfy the requirements of MoveConstructible (Table 20) and of MoveAssignable (Table 22).

It therefore rather just may call it, depending on the implementation. This answer may also provide some information on that.

Upvotes: 2

Related Questions