aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPatrick Palka <ppalka@redhat.com>2022-04-15 14:41:14 -0400
committerPatrick Palka <ppalka@redhat.com>2022-04-15 14:41:14 -0400
commit7e76cef873342a66408c126abceaf7dbddd3f477 (patch)
tree8a816011c97dd3edf618d648833df78980329f55
parenteb3f2e9348e8057f4219859a96739ff1ba350611 (diff)
downloadgcc-7e76cef873342a66408c126abceaf7dbddd3f477.zip
gcc-7e76cef873342a66408c126abceaf7dbddd3f477.tar.gz
gcc-7e76cef873342a66408c126abceaf7dbddd3f477.tar.bz2
libstdc++: Avoid double-deref of __first in ranges::minmax [PR104858]
PR libstdc++/104858 libstdc++-v3/ChangeLog: * include/bits/ranges_algo.h (__minmax_fn): Avoid dereferencing __first twice at the start. * testsuite/25_algorithms/minmax/constrained.cc (test06): New test.
-rw-r--r--libstdc++-v3/include/bits/ranges_algo.h2
-rw-r--r--libstdc++-v3/testsuite/25_algorithms/minmax/constrained.cc30
2 files changed, 31 insertions, 1 deletions
diff --git a/libstdc++-v3/include/bits/ranges_algo.h b/libstdc++-v3/include/bits/ranges_algo.h
index 62dc605..3d30fb1 100644
--- a/libstdc++-v3/include/bits/ranges_algo.h
+++ b/libstdc++-v3/include/bits/ranges_algo.h
@@ -3084,7 +3084,7 @@ namespace ranges
auto __last = ranges::end(__r);
__glibcxx_assert(__first != __last);
auto __comp_proj = __detail::__make_comp_proj(__comp, __proj);
- minmax_result<range_value_t<_Range>> __result = {*__first, *__first};
+ minmax_result<range_value_t<_Range>> __result = {*__first, __result.min};
if (++__first == __last)
return __result;
else
diff --git a/libstdc++-v3/testsuite/25_algorithms/minmax/constrained.cc b/libstdc++-v3/testsuite/25_algorithms/minmax/constrained.cc
index 90882af..5986404 100644
--- a/libstdc++-v3/testsuite/25_algorithms/minmax/constrained.cc
+++ b/libstdc++-v3/testsuite/25_algorithms/minmax/constrained.cc
@@ -20,6 +20,7 @@
#include <algorithm>
#include <string>
+#include <utility>
#include <vector>
#include <testsuite_hooks.h>
#include <testsuite_iterators.h>
@@ -129,6 +130,34 @@ test05()
VERIFY( result.min == "a"s && result.max == "c"s );
}
+struct A {
+ A() = delete;
+ A(int i) : i(i) { }
+ A(const A&) = default;
+ A(A&& other) : A(std::as_const(other)) { ++move_count; }
+ A& operator=(const A&) = default;
+ A& operator=(A&& other) {
+ ++move_count;
+ return *this = std::as_const(other);
+ };
+ friend auto operator<=>(const A&, const A&) = default;
+ static inline int move_count = 0;
+ int i;
+};
+
+void
+test06()
+{
+ // PR libstdc++/104858
+ // Verify ranges::minmax doesn't dereference the iterator for the first
+ // element in the range twice.
+ A a(42);
+ ranges::subrange r = {std::move_iterator(&a), std::move_sentinel(&a + 1)};
+ auto result = ranges::minmax(r);
+ VERIFY( A::move_count == 1 );
+ VERIFY( result.min.i == 42 && result.max.i == 42 );
+}
+
int
main()
{
@@ -137,4 +166,5 @@ main()
test03();
test04();
test05();
+ test06();
}