https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112349
Bug ID: 112349 Summary: ranges::max makes unecessary copies Product: gcc Version: 13.2.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: ted at lyncon dot se Target Milestone: --- From: https://stackoverflow.com/questions/77409266/why-does-gcc-copy-object-for-each-comparison-in-stdrangesmax OP's sample program shows a copy being made for each comparison: ``` #include <algorithm> #include <iostream> #include <ranges> #include <vector> struct A { A() = default; A(const A&) { std::cout << "Copy\n"; } A(A&&) noexcept { std::cout << "Move\n"; } A& operator=(const A&) { std::cout << "Copy assigned\n"; return *this; } A& operator=(A&&) noexcept { std::cout << "Move assigned\n"; return *this; } int x = 10; }; int main() { std::vector<A> vec(10); std::cout << "Init\n"; std::cout << std::ranges::max(vec, [](const auto& a, const auto& b) { std::cout << "cmp" << std::endl; return a.x < b.x; }).x; } ``` I _think_ the proper solution is to not copy `__first` into `__tmp` in `operator()`: ``` template<input_range _Range, typename _Proj = identity, indirect_strict_weak_order<projected<iterator_t<_Range>, _Proj>> _Comp = ranges::less> requires indirectly_copyable_storable<iterator_t<_Range>, range_value_t<_Range>*> constexpr range_value_t<_Range> operator()(_Range&& __r, _Comp __comp = {}, _Proj __proj = {}) const { auto __first = ranges::begin(__r); auto __last = ranges::end(__r); __glibcxx_assert(__first != __last); auto __result = *__first; while (++__first != __last) { auto __tmp = *__first; // <- COPY if (std::__invoke(__comp, std::__invoke(__proj, __result), std::__invoke(__proj, __tmp))) __result = std::move(__tmp); } return __result; } ``` By changing it to ```c++ auto& __tmp = *__first; ``` ...or just supplying `*__first` to `std::__invoke` it doesn't do copies in OP's example but it may have other consequences. Worth looking in to anyway.