simple-socket library 1.1.5

SocketHandle.h

Go to the documentation of this file.
00001 #ifndef NET_SocketHandle_h__
00002 #define NET_SocketHandle_h__
00003 
00004 #include <unistd.h>
00005 #include "TempFailure.h"
00006 
00007 namespace NET
00008 {
00009     template<class>
00010     class SocketHandle_Ref;
00011 
00012     class TCPSocket;
00013     class SCTPSocket;
00014 
00016 
00042     template<class Socket>
00043     class SocketHandle
00044     {
00045     public:
00046         friend class TCPSocket;
00047         friend class SCTPSocket;
00048 
00050         typedef Socket socket_type;
00051 
00053         SocketHandle() : m_sockfd(-1) {}
00054 
00056         SocketHandle( SocketHandle& other)
00057         : m_sockfd( other.release()) {}
00058 
00060         SocketHandle( SocketHandle_Ref<Socket> other)
00061         : m_sockfd( other.sockfd) {}
00062 
00063         operator SocketHandle_Ref<Socket>()
00064         { return SocketHandle_Ref<Socket>( release()); }
00066 
00068         SocketHandle&
00069         operator=( SocketHandle& other)
00070         {
00071             reset( other.release());
00072             return *this;
00073         }
00074 
00076         SocketHandle&
00077         operator=( SocketHandle_Ref<Socket> other)
00078         {
00079             reset( other.sockfd);
00080             return *this;
00081         }
00083 
00084         ~SocketHandle() { reset(); }
00085 
00087 
00093         operator bool() const { return m_sockfd >= 0; }
00094 
00095     private:
00097         explicit SocketHandle( int sockfd) : m_sockfd(sockfd) {}
00098 
00103         int release()
00104         {
00105             int tmp = m_sockfd;
00106             m_sockfd = -1;
00107             return tmp;
00108         }
00109 
00111 
00115         void reset( int fd = -1)
00116         {
00117             if( fd != m_sockfd)
00118             {
00119                 TEMP_FAILURE_RETRY (::close(m_sockfd));
00120                 m_sockfd = fd;
00121             }
00122         }
00123 
00124         int m_sockfd;
00125     };
00126 
00129     template<class Socket>
00130     class SocketHandle_Ref
00131     {
00132         int sockfd;
00133 
00134         friend class SocketHandle<Socket>;
00135         explicit SocketHandle_Ref( int sockfd) : sockfd(sockfd) {}
00136     };
00138 
00139 } // namespace NET
00140 
00141 #endif // NET_SocketHandle_h__