title: How do you correctly close sockets in boost::asio?
body: <p>I am trying to wrap my head around resource management in boost::asio. I am seeing callbacks called after the corresponding sockets are already destroyed. A good example of this is in the boost::asio official example: <a href="http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/example/cpp11/chat/chat_client.cpp" rel="noreferrer">http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/example/cpp11/chat/chat_client.cpp</a></p>
  
  <p>I am particularly concerned with the close method:</p>
  
  <pre><code>void close()
  {
     io_service_.post([this]() { socket_.close(); });
  }
  </code></pre>
  
  <p>If you call this function and afterwards destruct chat_client instance that holds socket_, socket_ will be destructed before the close method is called on it. Also any pending async_* callbacks can be called after the chat_client has been destroyed.</p>
  
  <p>How would you correctly handle this?</p>