4 Use of shared_ptr for asynchronous tasks
Christopher Kohlhoff tends to write classes that subclass std::enable_shared_from_this, for classes that manage the objects on which async operations can be posted (such as a socket or a deadline timer). When a lambda is created it holds a shared_ptr to the object, ensuring that the object is kept alive by the lambda.
For example:
class MyClass : public std::enable_shared_from_this<MyClass>
{
void do_async_thing()
{
auto self(shared_from_this());
boost::asio::post(context_,
[this, self]()
{
// do something
});
}
boost::asio::io_context& context_;
}
We shall follow this design pattern, therefore object instances of the following classes shall be reference counted via shared_ptr:
- LazyFlusher
- LazyCheckPointer
- LazyCleaner
- LazyWriter
- CSpace
- TcpMsgServer
- TcpMsgClient
- TcpMsgSession
The LSS shall use shared_ptr as follows:
class LazyWriter
{
std::shared_ptr<LazyFlusher> lazyFlusher_;
};
class SegmentWriter
{
std::shared_ptr<LazyWriter> lazyWriter_;
};
class LSS
{
SegmentWriter segmentWriter_;
std::shared_ptr<LazyCleaner> lazyCleaner_;
std::shared_ptr<LazyCheckPointer> lazyCheckPointer_;
};