• Lambda passed through a std::sort recursion

    From Bonita Montero@21:1/5 to All on Sun Nov 19 12:04:18 2023
    I was interested in whether my C++ implementations pass the lambda you
    supply with std::sort through the recursion of sort by coping. libstdc++
    (g++) and libc++ (clang++) copy the lambda at each recursion level. MSVC
    stores the lambda only once.

    #include <iostream>
    #include <vector>
    #include <random>
    #include <unordered_map>
    #include <climits>
    #include <algorithm>

    using namespace std;

    int main( int argc, char **argv )
    {
    mt19937_64 mt;
    uniform_int_distribution<int> uid( INT_MAX, INT_MAX );
    vector<int> vi;
    vi.reserve( 1'000 );
    for( size_t i = vi.capacity(); i--; )
    vi.emplace_back( uid( mt ) );
    unordered_map<void const *, size_t> addresses;
    bool invert = argc > 1;
    sort( vi.begin(), vi.end(),
    [&, invert = invert]( int lhs, int rhs )
    {
    ++addresses[&invert];
    if( !invert )
    return lhs < rhs;
    else
    return rhs < lhs;
    } );
    for( auto &pCount : addresses )
    cout << pCount.first << ": " << pCount.second << endl;
    }

    I think for std::sort it would be the best to store the complete
    state the lambda refers to as a static or thread_local variable
    that the lambda itself doesn't need any state to be copied that
    there's actually no parameter passed through the recursion.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)