MCPcopy Create free account
hub / github.com/Extra-Creativity/Modern-Cpp-Basics / Socket

Class Socket

08-String & Stream/example/src/Socket.h:25–91  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

23{
24
25class Socket
26{
27#ifdef _WIN32
28 inline static constexpr SOCKET s_invalidSocket_ = INVALID_SOCKET;
29 SOCKET socket_{ s_invalidSocket_ };
30#else
31 inline static constexpr int s_invalidSocket_ = -1;
32 int socket_{ s_invalidSocket_ };
33#endif
34
35public:
36 enum class Tag
37 {
38 Listen,
39 Accept,
40 Connect
41 };
42
43 Socket() = default;
44
45 // Listen socket or connect socket.
46 Socket(const char *ip, std::uint16_t port, Tag tag);
47
48 // Accept socket; To distinguish it from copy ctor (in fact socket doesn't
49 // have it), add a tag param.
50 Socket(const Socket &listenSock, Tag tag);
51
52 Socket(Socket &&another) noexcept
53 : socket_{ std::exchange(another.socket_, s_invalidSocket_) }
54 {
55 }
56 Socket &operator=(Socket &&another) noexcept
57 {
58 if (*this)
59 Clean_();
60 socket_ = std::exchange(another.socket_, s_invalidSocket_);
61 return *this;
62 }
63
64 ~Socket()
65 {
66 if (*this)
67 Clean_();
68 }
69
70 // Clean and reset.
71 void Close()
72 {
73 if (*this)
74 {
75 Clean_();
76 socket_ = s_invalidSocket_;
77 }
78 }
79 explicit operator bool() const noexcept
80 {
81 return socket_ != s_invalidSocket_;
82 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected