socket_holder.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // detail/socket_holder.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2018 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 BOOST_ASIO_DETAIL_SOCKET_HOLDER_HPP
  11. #define BOOST_ASIO_DETAIL_SOCKET_HOLDER_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #include <boost/asio/detail/noncopyable.hpp>
  17. #include <boost/asio/detail/socket_ops.hpp>
  18. #include <boost/asio/detail/push_options.hpp>
  19. namespace boost {
  20. namespace asio {
  21. namespace detail {
  22. // Implement the resource acquisition is initialisation idiom for sockets.
  23. class socket_holder
  24. : private noncopyable
  25. {
  26. public:
  27. // Construct as an uninitialised socket.
  28. socket_holder()
  29. : socket_(invalid_socket)
  30. {
  31. }
  32. // Construct to take ownership of the specified socket.
  33. explicit socket_holder(socket_type s)
  34. : socket_(s)
  35. {
  36. }
  37. // Destructor.
  38. ~socket_holder()
  39. {
  40. if (socket_ != invalid_socket)
  41. {
  42. boost::system::error_code ec;
  43. socket_ops::state_type state = 0;
  44. socket_ops::close(socket_, state, true, ec);
  45. }
  46. }
  47. // Get the underlying socket.
  48. socket_type get() const
  49. {
  50. return socket_;
  51. }
  52. // Reset to an uninitialised socket.
  53. void reset()
  54. {
  55. if (socket_ != invalid_socket)
  56. {
  57. boost::system::error_code ec;
  58. socket_ops::state_type state = 0;
  59. socket_ops::close(socket_, state, true, ec);
  60. socket_ = invalid_socket;
  61. }
  62. }
  63. // Reset to take ownership of the specified socket.
  64. void reset(socket_type s)
  65. {
  66. reset();
  67. socket_ = s;
  68. }
  69. // Release ownership of the socket.
  70. socket_type release()
  71. {
  72. socket_type tmp = socket_;
  73. socket_ = invalid_socket;
  74. return tmp;
  75. }
  76. private:
  77. // The underlying socket.
  78. socket_type socket_;
  79. };
  80. } // namespace detail
  81. } // namespace asio
  82. } // namespace boost
  83. #include <boost/asio/detail/pop_options.hpp>
  84. #endif // BOOST_ASIO_DETAIL_SOCKET_HOLDER_HPP