diff --git a/client_http.hpp b/client_http.hpp index fd2471f..5d1a1d0 100644 --- a/client_http.hpp +++ b/client_http.hpp @@ -100,11 +100,13 @@ namespace SimpleWeb { return; } timer = std::unique_ptr(new asio::steady_timer(get_socket_executor(*socket), std::chrono::seconds(seconds))); - auto self = this->shared_from_this(); - timer->async_wait([self](const error_code &ec) { + std::weak_ptr self_weak(this->shared_from_this()); // To avoid keeping Connection instance alive longer than needed + timer->async_wait([self_weak](const error_code &ec) { if(!ec) { - error_code ec; - self->socket->lowest_layer().cancel(ec); + if(auto self = self_weak.lock()) { + error_code ec; + self->socket->lowest_layer().cancel(ec); + } } }); } diff --git a/server_http.hpp b/server_http.hpp index d86e5c7..290d3f4 100644 --- a/server_http.hpp +++ b/server_http.hpp @@ -277,10 +277,12 @@ namespace SimpleWeb { } timer = std::unique_ptr(new asio::steady_timer(get_socket_executor(*socket), std::chrono::seconds(seconds))); - auto self = this->shared_from_this(); - timer->async_wait([self](const error_code &ec) { - if(!ec) - self->close(); + std::weak_ptr self_weak(this->shared_from_this()); // To avoid keeping Connection instance alive longer than needed + timer->async_wait([self_weak](const error_code &ec) { + if(!ec) { + if(auto self = self_weak.lock()) + self->close(); + } }); }