00001 // 00002 // socket_holder.hpp 00003 // ~~~~~~~~~~~~~~~~~ 00004 // 00005 // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) 00006 // 00007 // Distributed under the Boost Software License, Version 1.0. (See accompanying 00008 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 00009 // 00010 00011 #ifndef ASIO_DETAIL_SOCKET_HOLDER_HPP 00012 #define ASIO_DETAIL_SOCKET_HOLDER_HPP 00013 00014 #if defined(_MSC_VER) && (_MSC_VER >= 1200) 00015 # pragma once 00016 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) 00017 00018 #include "asio/detail/push_options.hpp" 00019 00020 #include "asio/detail/noncopyable.hpp" 00021 #include "asio/detail/socket_ops.hpp" 00022 00023 namespace asio { 00024 namespace detail { 00025 00026 // Implement the resource acquisition is initialisation idiom for sockets. 00027 class socket_holder 00028 : private noncopyable 00029 { 00030 public: 00031 // Construct as an uninitialised socket. 00032 socket_holder() 00033 : socket_(invalid_socket) 00034 { 00035 } 00036 00037 // Construct to take ownership of the specified socket. 00038 explicit socket_holder(socket_type s) 00039 : socket_(s) 00040 { 00041 } 00042 00043 // Destructor. 00044 ~socket_holder() 00045 { 00046 if (socket_ != invalid_socket) 00047 { 00048 asio::error_code ec; 00049 socket_ops::close(socket_, ec); 00050 } 00051 } 00052 00053 // Get the underlying socket. 00054 socket_type get() const 00055 { 00056 return socket_; 00057 } 00058 00059 // Reset to an uninitialised socket. 00060 void reset() 00061 { 00062 if (socket_ != invalid_socket) 00063 { 00064 asio::error_code ec; 00065 socket_ops::close(socket_, ec); 00066 socket_ = invalid_socket; 00067 } 00068 } 00069 00070 // Reset to take ownership of the specified socket. 00071 void reset(socket_type s) 00072 { 00073 reset(); 00074 socket_ = s; 00075 } 00076 00077 // Release ownership of the socket. 00078 socket_type release() 00079 { 00080 socket_type tmp = socket_; 00081 socket_ = invalid_socket; 00082 return tmp; 00083 } 00084 00085 private: 00086 // The underlying socket. 00087 socket_type socket_; 00088 }; 00089 00090 } // namespace detail 00091 } // namespace asio 00092 00093 #include "asio/detail/pop_options.hpp" 00094 00095 #endif // ASIO_DETAIL_SOCKET_HOLDER_HPP