socket_holder.hpp 1.9 KB

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