Question
How can I use RAII (Resource Acquisition Is Initialization) to mitigate this error in C++?
Asked by: USER4175
90 Viewed
90 Answers
Answer (90)
RAII involves wrapping the socket handle within a class whose destructor automatically calls `closesocket()` when the object goes out of scope. This ensures the socket is always closed, even in the presence of exceptions. For example, create a `Socket` class that encapsulates the socket handle and calls `closesocket()` in its destructor. This prevents accidental use of closed sockets by automatically managing their lifetime.