What alternatives need to be followed for the following code to make safe asynchronous callbacks on an object?
class MyClass : public std::enable_shared_from_this<MyClass>
{
private:
void fetchResults()
{
std::weak_ptr<MyClass> weakSelf = shared_from_this();
m_service.getResultAsync(
,
[weakSelf](Result r)
{
auto self = weakSelf.lock();
if (self)
{
self->workFinishedWithResult(std::move(r));
}
});
}
void workFinishedWithResult(Result r) {
std::shared_ptr<Service> m_service;
};
I would like to avoid use enable_shared_from_this(and avoid clients m_servicerequiring it for a very common use case), but it seems difficult to extend the lifetime MyClassonce inside the callback without it.
Capturing thislambda instead and attempting to cancel it in the MyClass destructor or prevent MyClass from being destroyed before the callback is complete is the path that leads to races, deadlocks, and loss of simplicity. I am pretty sure that capturing 'this' cannot be safe.
, MyClass shared_ptr<Service> , , , ( enable_shared_from_this), , . , MyClass, , Service, MyClass, , .
, :
enable_shared_from_this " " ( )- MyClass
Service&, . - / , , - ( ,
MyClass, ).
? enable_shared_from_this async ++?