isocpp / isocpp/CppCoreGuidelines
[Proposal] Coroutine class functions on refcounted classes should keep the class instance alive until completion (CP.coro section)
Nobody has claimed this yet.
- Dominant language
- CSS
- Stars
- 45.3k
- Forks
- 5.6k
- PR merge metrics
- No merged PRs in 30d
Description
Coroutine class functions on refcounted classes should keep the class instance alive until completion
Reason
When a coroutine class method reaches the first suspension point, such as co_await, the synchronous portion of the coroutine returns. After that point there is nothing in the coroutine keeping the reference count from going to zero and destructing the instance pointed to by the the this pointer. This can be avoided by ensuring that a reference count is held in a local variable that will live until the coroutine completes.
In some cases all access to class fields happen before the first suspension point, so these accesses are safe. However, it is fragile to rely on that because subsequent changes to the function may add or move suspension points which would reintroduce this class of bug. It is safer to always ensure a reference count is held for the lifetime of the coroutine.
Example, Bad
class Class: public std::enable_shared_from_this<Class>
{
std::future<int> do_something()
{
co_await something();
return m_classField; // DANGER: the this pointer may have been freed while the coroutine was suspended
}
private:
int m_classField{};
};
Example, Good
class Class: public std::enable_shared_from_this<Class>
{
std::future<int> do_something()
{
const auto strong_this = shared_from_this();
co_await something();
return m_classField; // OK: the this pointer is kept alive by strong_this
}
private:
int m_classField{};
};
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 by reading the CP.coro section and the issue's bad and good coroutine examples. Determine how the guidelines should express keeping a refcounted class instance alive across suspension, including the stated rationale and scope. Done means the section clearly documents this lifetime requirement with an appropriate guideline and example.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100