[libcxx-commits] [libcxx] [libcxx] Optimize std::generate for segmented iterators (PR #163006)

A. Jiang via libcxx-commits libcxx-commits at lists.llvm.org
Sat Oct 18 02:09:23 PDT 2025


================
@@ -20,8 +22,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD
 template <class _ForwardIterator, class _Generator>
 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
 generate(_ForwardIterator __first, _ForwardIterator __last, _Generator __gen) {
-  for (; __first != __last; ++__first)
-    *__first = __gen();
+  std::for_each(__first, __last, [&](decltype(*__first) __element) { __element = __gen(); });
----------------
frederick-vs-ja wrote:

Let's keep forwarding.
```suggestion
  using __iter_ref = decltype(*__first);
  std::for_each(__first, __last, [&](__iter_ref __element) { std::forward<__iter_ref>(__element) = __gen(); });
```

It seems that we are not testing rvalue-only assignment for `std::generate`. Perhaps we should add the tests in a future PR,

https://github.com/llvm/llvm-project/pull/163006


More information about the libcxx-commits mailing list