Ignoring Swap Overload

I overloaded the swap function for my class, as in this answer , but when sorting ( std::sort), the compiler still uses std::swap. I see no difference between my approach and what is indicated in the linked answer. Here's the 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 an executable example provided here .

+4
source share
1 answer

The standard does not indicate in its specification (§25.4.1.1 [alg.sort]) what it std::sortis actually guaranteed to call swap, it only mentions that the type must conform to certain concepts, t interpret as a guarantee:

: RandomAccessIterator ValueSwappable (17.6.3.2). * MoveConstructible ( 20) MoveAssignable ( 22).

, , , . .

+2

Source: https://habr.com/ru/post/1688736/


All Articles