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

Class Socket

08-String & Stream/example-answer/src/Socket.h:25–95  ·  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 == &another)
59 {
60 return *this;
61 }
62 if (*this)
63 Clean_();
64 socket_ = std::exchange(another.socket_, s_invalidSocket_);
65 return *this;
66 }
67
68 ~Socket()
69 {
70 if (*this)
71 Clean_();
72 }
73
74 // Clean and reset.
75 void Close()
76 {
77 if (*this)
78 {
79 Clean_();
80 socket_ = s_invalidSocket_;
81 }
82 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected