isocpp / isocpp/CppCoreGuidelines
CP.53 - Parameters to coroutines should not be passed by reference - seems wrong
Nobody has claimed this yet.
- Dominant language
- CSS
- Stars
- 45.3k
- Forks
- 5.6k
- PR merge metrics
- No merged PRs in 30d
Description
CP.53: Parameters to coroutines should not be passed by reference
This is the issue that suggested rule #1806
I think this rule might be wrong and makes the code bases more bug-prone. It is quite common to manage the lifetime of coroutines within the scope that they are spawned and pass const or mutable reference to the child coroutines. That is what we can expect from structured concurrency.
For example, here we launch two tasks and wait for them to complete:
auto socket = asio::ip::tcp::socket{ executor };
co_await socket.async_connect(endpoint, asio::deferred);
auto receive_task = [](asio::ip::tcp::socket &socket) -> asio::awaitable< void >
{
// ..
};
auto send_task = [](asio::ip::tcp::socket &socket) -> asio::awaitable< void >
{
// ..
};
co_await wait_for_all(receive_task(socket), send_task(socket));
Here we spawn one coroutine per connection and wait for them to complete at the end of the scope:
asio::awaitable< void > handle_session(asio::ip::tcp::socket socket, Database & database);
auto database = Database{};
auto task_group = TaskGroup{};
auto acceptor = asio::ip::tcp::acceptor{ executor, endpoint };
for (;;)
{
auto [ec, socket] = co_await acceptor.async_accept(asio::as_tuple(asio::deferred));
if (ec)
break;
task_group.spawn(handle_session(std::move(socket), database));
}
co_await task_group.join();
Aside from these examples, every coroutine member function has an implicit reference to the instance.
So, if this guideline prohibits references in coroutine parameters and suggests allocating objects on the heap and passing them as shared_ptr, it would be against structured concurrency and can create a shared pointer spaghetti.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked CP.53 rule and the issue that suggested rule #1806, then examine the structured-concurrency examples in this report. Determine whether the guideline's wording or scope should change, and document a decision that addresses reference lifetimes, coroutine member functions, and the proposed shared_ptr alternative.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100