From 514a135e0cf95d606a6eaa006f1866dd4438eab8 Mon Sep 17 00:00:00 2001 From: eidheim Date: Mon, 27 May 2019 21:13:28 +0200 Subject: [PATCH] Improved set_timeout(): no longer keeps connection alive longer than necessary. --- client_http.hpp | 10 ++++++---- server_http.hpp | 10 ++++++---- 2 files changed, 12 insertions(+), 8 deletions(-) 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(); + } }); }