Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.Asio socket destructor closes connection?

What exactly does the destructor of boost::asio::ip::tcp::socket do? I can't tell, even after scouring Boost docs and source code, if I need to use

socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
socket->close();

before calling

delete socket;

Do I need to close the socket manually, or does the destructor handle this?

like image 308
owacoder Avatar asked Oct 02 '16 01:10

owacoder


3 Answers

When a socket is destroyed, it will be closed as-if by socket.close(ec) during the destruction of the socket.

I/O objects, such as socket, derive from basic_io_object. Within the basic_io_object destructor, destroy() will be invoked on the I/O object's I/O service, passing in an instance of the implementation_type on which the I/O object's service will operate. In the case of socket, destroy() will be invoked on a type that fulfills the SocketService type requirement, closing the underlying socket. In the documentation below, a is an instance of a socket service class, and b is an instance of the implementation_type for the socket service class:

a.destroy(b):

[...] Implicitly cancels asynchronous operations, as if by calling a.close(b, ec).

a.close(b, ec):

If a.is_open() is true, causes any outstanding asynchronous operations to complete as soon as possible. Handlers for cancelled operations shall be passed the error code error::operation_aborted.

post: !a.is_open(b).

like image 187
Tanner Sansbury Avatar answered Oct 20 '22 14:10

Tanner Sansbury


No you don't need to close it. Though it might be cleaner to do so, if you want to report any errors surrounding protocol shutdown.

The destructor just /appears/ to be empty, that's a good sign of Modern C++:

  • http://en.cppreference.com/w/cpp/language/rule_of_three
  • Rule Of Zero
like image 4
sehe Avatar answered Oct 20 '22 14:10

sehe


The answers have skipped over the issue of shutdown(). From the close() documentation, "For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket".

If deleting the socket does an implicit close, it seems that a call to shutdown() is still recommended before deleting it.

like image 4
edj Avatar answered Oct 20 '22 13:10

edj