[Bug libstdc++/123182] repeated calls to std::views::filter may give wrong results
redi at gcc dot gnu.org
gcc-bugzilla@gcc.gnu.org
Thu Dec 18 11:18:54 GMT 2025
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=123182
Jonathan Wakely <redi at gcc dot gnu.org> changed:
What |Removed |Added
----------------------------------------------------------------------------
Resolution|--- |INVALID
Status|UNCONFIRMED |RESOLVED
--- Comment #1 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to Pavel Šimerda from comment #0)
> When you create a `std::views::filter` over a `std::vector`, it works
> perfect the first time but if you change the first item of the vector from
> matching the filter condition to not matching it, you may still have it in
> the result.
Yes. Don't do that.
https://brevzin.github.io/c++/2023/04/25/mutating-filter/ explains this in
detail.
Modifying the underlying range in a way that changes whether an element matches
the filter predicate results in undefined behaviour, see
[range.filter.iterator]/1 in the C++ standard:
Modification of the element a filter_view::iterator denotes is permitted,
but results in undefined behavior if the resulting value does not satisfy
the filter predicate.
> I would assume views would lazily take vector's `begin()` and `end()` and do
> the filtering each time it is materialized.
No, the first time you call begin() the view finds the first matching element
and then caches that iterator, so that calling begin() again is fast.
This is a well known property of filter_view, e.g. see
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3329r0.pdf
But the standard is very unlikely to change and libstdc++ is implementing the
standard correctly.
More information about the Gcc-bugs
mailing list