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