simple-socket library 1.2.0
SocketHandle.h
Go to the documentation of this file.
1#ifndef NET_SocketHandle_h__
2#define NET_SocketHandle_h__
3
4#include <unistd.h>
5#include "TempFailure.h"
6
7namespace NET
8{
9 template<class>
11
12 class TCPSocket;
13 class SCTPSocket;
14
16
47 template<class Socket>
49 {
50 public:
51 friend class TCPSocket;
52 friend class SCTPSocket;
53
55 typedef Socket socket_type;
56
58 SocketHandle() : m_sockfd(-1) {}
59
62 : m_sockfd( other.release()) {}
63
66 : m_sockfd( other.sockfd) {}
67
68 operator SocketHandle_Ref<Socket>()
69 { return SocketHandle_Ref<Socket>( release()); }
71
75 {
76 reset( other.release());
77 return *this;
78 }
79
83 {
84 reset( other.sockfd);
85 return *this;
86 }
88
89 ~SocketHandle() { reset(); }
90
92
99 operator bool() const { return m_sockfd >= 0; }
100
101 private:
103 explicit SocketHandle( int sockfd) : m_sockfd(sockfd) {}
104
109 int release()
110 {
111 int tmp = m_sockfd;
112 m_sockfd = -1;
113 return tmp;
114 }
115
117
121 void reset( int fd = -1)
122 {
123 if( fd != m_sockfd)
124 {
125 TEMP_FAILURE_RETRY (::close(m_sockfd));
126 m_sockfd = fd;
127 }
128 }
129
130 int m_sockfd;
131 };
132
135 template<class Socket>
136 class SocketHandle_Ref
137 {
138 int sockfd;
139
140 friend class SocketHandle<Socket>;
141 explicit SocketHandle_Ref( int sockfd) : sockfd(sockfd) {}
142 };
144
145} // namespace NET
146
147#endif // NET_SocketHandle_h__
#define TEMP_FAILURE_RETRY(expression)
Definition TempFailure.h:8
Definition CANFrame.h:7
SCTP socket class.
Definition SCTPSocket.h:17
A simple class to provide strict ownership of socket handles.
SocketHandle(SocketHandle &other)
copy constructor using move semantics
SocketHandle()
constructs an invalid socket handle
SocketHandle & operator=(SocketHandle &other)
assignment operator using move semantics
TCP socket class.
Definition TCPSocket.h:11