Skip to content

Commit

Permalink
Fix unintended shallow copying when used with std::views::take (issue…
Browse files Browse the repository at this point in the history
… 261) (#263)

* Fix for issue 261
Enables `view` concept on `generator` so that lvalue references cannot be accepts by `std::views:take`,
which in turn would lead to erronious behavior.

* Added a test case to check std::ranges:view concept, just like std::generator
  • Loading branch information
mikucionisaau authored May 31, 2024
1 parent 3e8a735 commit d4a5515
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion include/coro/generator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ class generator_iterator
} // namespace detail

template<typename T>
class generator
class generator : public std::ranges::view_base
{
public:
using promise_type = detail::generator_promise<T>;
Expand Down
34 changes: 34 additions & 0 deletions test/test_generator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,37 @@ TEST_CASE("generator infinite incrementing integer yield", "[generator]")
}
}
}

TEST_CASE("generator satisfies view concept for compatibility with std::views::take")
{
auto counter = size_t{0};
auto natural = [n = counter]() mutable -> coro::generator<size_t> {
while (true)
co_yield ++n;
};
auto nat = natural();
static_assert(std::ranges::view<decltype(nat)>, "does not satisfy view concept");
SECTION("Count the items")
{
for (auto&& n : natural() | std::views::take(5))
{
++counter;
REQUIRE(n == counter);
}
REQUIRE(counter == 5);
}
SECTION("Not supported when std::ranges::view is satisfied, see issue 261")
{
/// the following may fail to compile to prevent loss of items in the std::views:take:
/*
for (auto&& n : nat | std::views::take(3)) {
++counter;
REQUIRE(n == counter); // expect 1, 2, 3
}
for (auto&& n : nat | std::views::take(3)) {
++counter;
REQUIRE(n == counter); // expect 4, 5, 6 (4 may get lost if view is not enabled)
}
*/
}
}

0 comments on commit d4a5515

Please sign in to comment.