I have a special network code. I use asio, but it really doesn't matter for this question. I guess there is no way to untie a socket other than closing it. The problem is that open(), bind()and listen()they can throw it away system_error. So I processed the code simple try/catch. Code written broken.
using namespace boost::asio;
class Thing
{
public:
ip::tcp::endpoint m_address;
ip::tcp::acceptor m_acceptor;
bool connect()
{
try
{
m_acceptor.open( m_address.protocol() );
m_acceptor.set_option( tcp::acceptor::reuse_address(true) );
m_acceptor.bind( m_address );
m_acceptor.listen();
m_acceptor.async_accept( );
}
catch( const boost::system::system_error& error )
{
assert(acceptor.is_open());
m_acceptor.close();
return false;
}
return true;
}
void disconnect()
{
m_acceptor.close();
}
};
The error is that the socket will not be able to connect, it will try to close it in the catch block and throw another system_error into the closure of the acceptor, which was never opened.
if( acceptor.is_open() ) catch, . , C - c++. , - open().
boost::system::error_code error;
acceptor.open( address.protocol, error );
if( ! error )
{
try
{
acceptor.set_option( tcp::acceptor::reuse_address(true) );
acceptor.bind( address );
acceptor.listen();
acceptor.async_accept( );
}
catch( const boost::system::system_error& error )
{
assert(acceptor.is_open());
acceptor.close();
return false;
}
}
return !error;
RAII try/catch?
, if( error condition ) ?