Clementine
completion_handler.hpp
1 //
2 // detail/completion_handler.hpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6 //
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 //
10 
11 #ifndef ASIO_DETAIL_COMPLETION_HANDLER_HPP
12 #define ASIO_DETAIL_COMPLETION_HANDLER_HPP
13 
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
15 # pragma once
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
17 
18 #include "asio/detail/config.hpp"
19 #include "asio/detail/fenced_block.hpp"
20 #include "asio/detail/handler_alloc_helpers.hpp"
21 #include "asio/detail/handler_work.hpp"
22 #include "asio/detail/memory.hpp"
23 #include "asio/detail/operation.hpp"
24 
25 #include "asio/detail/push_options.hpp"
26 
27 namespace asio {
28 namespace detail {
29 
30 template <typename Handler, typename IoExecutor>
31 class completion_handler : public operation
32 {
33 public:
34  ASIO_DEFINE_HANDLER_PTR(completion_handler);
35 
36  completion_handler(Handler& h, const IoExecutor& io_ex)
37  : operation(&completion_handler::do_complete),
38  handler_(ASIO_MOVE_CAST(Handler)(h)),
39  work_(handler_, io_ex)
40  {
41  }
42 
43  static void do_complete(void* owner, operation* base,
44  const asio::error_code& /*ec*/,
45  std::size_t /*bytes_transferred*/)
46  {
47  // Take ownership of the handler object.
48  completion_handler* h(static_cast<completion_handler*>(base));
49  ptr p = { asio::detail::addressof(h->handler_), h, h };
50 
51  ASIO_HANDLER_COMPLETION((*h));
52 
53  // Take ownership of the operation's outstanding work.
55  ASIO_MOVE_CAST2(handler_work<Handler, IoExecutor>)(
56  h->work_));
57 
58  // Make a copy of the handler so that the memory can be deallocated before
59  // the upcall is made. Even if we're not about to make an upcall, a
60  // sub-object of the handler may be the true owner of the memory associated
61  // with the handler. Consequently, a local copy of the handler is required
62  // to ensure that any owning sub-object remains valid until after we have
63  // deallocated the memory here.
64  Handler handler(ASIO_MOVE_CAST(Handler)(h->handler_));
65  p.h = asio::detail::addressof(handler);
66  p.reset();
67 
68  // Make the upcall if required.
69  if (owner)
70  {
71  fenced_block b(fenced_block::half);
72  ASIO_HANDLER_INVOCATION_BEGIN(());
73  w.complete(handler, handler);
74  ASIO_HANDLER_INVOCATION_END;
75  }
76  }
77 
78 private:
79  Handler handler_;
81 };
82 
83 } // namespace detail
84 } // namespace asio
85 
86 #include "asio/detail/pop_options.hpp"
87 
88 #endif // ASIO_DETAIL_COMPLETION_HANDLER_HPP
Definition: chrono.h:284
Definition: null_fenced_block.hpp:25
Class to represent an error code value.
Definition: error_code.hpp:80
Definition: any_io_executor.hpp:28
Definition: completion_handler.hpp:31