diff --git a/libcxx/include/__algorithm/ranges_minmax.h b/libcxx/include/__algorithm/ranges_minmax.h --- a/libcxx/include/__algorithm/ranges_minmax.h +++ b/libcxx/include/__algorithm/ranges_minmax.h @@ -74,6 +74,15 @@ if constexpr (forward_range<_Range>) { auto __result = std::__minmax_element_impl(__first, __last, __comp, __proj); + // We can dereference normal pointers many times but some iterators could move their value after + // dereferencing so we should dereference them only once. The if constexpr is a pure optimization, we + // don't want an additional branch for normal pointers. + if constexpr (!is_pointer_v>) { + if (__result.first == __result.second) { + auto __temp = static_cast<_ValueT>(*__result.first); + return {__temp, std::move(__temp)}; + } + } return {*__result.first, *__result.second}; } else { // input_iterators can't be copied, so the implementation for input_iterators has to store