completion_handler.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // detail/completion_handler.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2011 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. #ifndef ASIO_DETAIL_COMPLETION_HANDLER_HPP
  11. #define ASIO_DETAIL_COMPLETION_HANDLER_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/config.hpp"
  16. #include "asio/detail/fenced_block.hpp"
  17. #include "asio/detail/handler_alloc_helpers.hpp"
  18. #include "asio/detail/handler_invoke_helpers.hpp"
  19. #include "asio/detail/operation.hpp"
  20. #include "asio/detail/push_options.hpp"
  21. namespace asio {
  22. namespace detail {
  23. template <typename Handler>
  24. class completion_handler : public operation
  25. {
  26. public:
  27. ASIO_DEFINE_HANDLER_PTR(completion_handler);
  28. completion_handler(Handler h)
  29. : operation(&completion_handler::do_complete),
  30. handler_(h)
  31. {
  32. }
  33. static void do_complete(io_service_impl* owner, operation* base,
  34. asio::error_code /*ec*/, std::size_t /*bytes_transferred*/)
  35. {
  36. // Take ownership of the handler object.
  37. completion_handler* h(static_cast<completion_handler*>(base));
  38. ptr p = { boost::addressof(h->handler_), h, h };
  39. // Make a copy of the handler so that the memory can be deallocated before
  40. // the upcall is made. Even if we're not about to make an upcall, a
  41. // sub-object of the handler may be the true owner of the memory associated
  42. // with the handler. Consequently, a local copy of the handler is required
  43. // to ensure that any owning sub-object remains valid until after we have
  44. // deallocated the memory here.
  45. Handler handler(h->handler_);
  46. p.h = boost::addressof(handler);
  47. p.reset();
  48. // Make the upcall if required.
  49. if (owner)
  50. {
  51. asio::detail::fenced_block b;
  52. asio_handler_invoke_helpers::invoke(handler, handler);
  53. }
  54. }
  55. private:
  56. Handler handler_;
  57. };
  58. } // namespace detail
  59. } // namespace asio
  60. #include "asio/detail/pop_options.hpp"
  61. #endif // ASIO_DETAIL_COMPLETION_HANDLER_HPP