@@ -2945,11 +2945,11 @@ namespace ranges
auto __result = *__first;
while (++__first != __last)
{
- auto __tmp = *__first;
+ auto&& __tmp = *__first;
if (std::__invoke(__comp,
std::__invoke(__proj, __result),
std::__invoke(__proj, __tmp)))
- __result = std::move(__tmp);
+ __result = std::forward<decltype(__tmp)>(__tmp);
}
return __result;
}
@@ -754,11 +754,11 @@ namespace ranges
auto __result = *__first;
while (++__first != __last)
{
- auto __tmp = *__first;
+ auto&& __tmp = *__first;
if (std::__invoke(__comp,
std::__invoke(__proj, __tmp),
std::__invoke(__proj, __result)))
- __result = std::move(__tmp);
+ __result = std::forward<decltype(__tmp)>(__tmp);
}
return __result;
}
@@ -73,10 +73,35 @@ test03()
VERIFY( ranges::max({2,3,1,4}, ranges::greater{}, std::negate<>{}) == 4 );
}
+void
+test04()
+{
+ // PR libstdc++/112349 - ranges::max/min make unnecessary copies
+ static int copies, moves;
+ struct A {
+ A(int m) : m(m) { }
+ A(const A& other) : m(other.m) { ++copies; }
+ A(A&& other) : m(other.m) { ++moves; }
+ A& operator=(const A& other) { m = other.m; ++copies; return *this; }
+ A& operator=(A&& other) { m = other.m; ++moves; return *this; }
+ int m;
+ };
+ A r[5] = {5, 4, 3, 2, 1};
+ ranges::max(r, std::less{}, &A::m);
+ VERIFY( copies == 1 );
+ VERIFY( moves == 0 );
+ copies = moves = 0;
+ A s[5] = {1, 2, 3, 4, 5};
+ ranges::max(s, std::less{}, &A::m);
+ VERIFY( copies == 5 );
+ VERIFY( moves == 0 );
+}
+
int
main()
{
test01();
test02();
test03();
+ test04();
}
@@ -73,10 +73,35 @@ test03()
VERIFY( ranges::min({2,3,1,4}, ranges::greater{}, std::negate<>{}) == 1 );
}
+void
+test04()
+{
+ // PR libstdc++/112349 - ranges::max/min make unnecessary copies
+ static int copies, moves;
+ struct A {
+ A(int m) : m(m) { }
+ A(const A& other) : m(other.m) { ++copies; }
+ A(A&& other) : m(other.m) { ++moves; }
+ A& operator=(const A& other) { m = other.m; ++copies; return *this; }
+ A& operator=(A&& other) { m = other.m; ++moves; return *this; }
+ int m;
+ };
+ A r[5] = {5, 4, 3, 2, 1};
+ ranges::min(r, std::less{}, &A::m);
+ VERIFY( copies == 5 );
+ VERIFY( moves == 0 );
+ copies = moves = 0;
+ A s[5] = {1, 2, 3, 4, 5};
+ ranges::min(s, std::less{}, &A::m);
+ VERIFY( copies == 1 );
+ VERIFY( moves == 0 );
+}
+
int
main()
{
test01();
test02();
test03();
+ test04();
}