[libcxx-commits] [libcxx] [libc++] Treat negative counts in copy_n & friends as no-ops (PR #207086)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu Jul 2 07:52:06 PDT 2026


================
@@ -63,6 +64,7 @@ __for_each_n(_InputIterator __first, _Size __orig_n, _Func&& __f, _Proj& __proj)
 template <class _InputIterator, class _Size, class _Func>
 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _InputIterator
 for_each_n(_InputIterator __first, _Size __orig_n, _Func __f) {
+  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__orig_n >= 0, "for_each_n requires a non-negative count");
----------------
ldionne wrote:

I think changing that would be a paper since it's technically a design change. I sent this email to LWG to check the temperature and CC'd you:

> 
> Hi,
> 
> While fixing [a libc++ bug](https://github.com/llvm/llvm-project/issues/193613) where copy_n, fill_n and generate_n crashed on negative counts, we noticed an inconsistency in how the standard treats a negative count:
> 
> - copy_n, fill_n and generate_n all define their effects in terms of max(0, n), so a negative n is well-defined and simply a no-op. The design intent of supporting negative counts is pretty clear from the wording.
> - for_each_n instead states "Preconditions: n >= 0 is true", making a negative n undefined behavior.
> 
> Is this divergence intentional? If not, I could write a (very) short paper to propose supporting negative counts in for_each_n, for consistency. I would have preferred a precondition everywhere instead, but the design intent in copy_n & friends is clear from the wording, so I have no plans to relitigate that.
> 
> Thanks,
> Louis

For now I think we should assume this is the intended design, and implement that.

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


More information about the libcxx-commits mailing list