Memory management in asynchronous C ++ code

I have been working with boost::asio for a while, and although I understand the concept of asynchronous calls, I am still somewhat stunned by the consequences of memory management. In ordinary synchronous code, the lifetime of an object is clear. But consider a scenario similar to the daily server case:

There may be several active connections that were accept ed. Each connection now sends and receives some data from the socket, does some work internally, and then decides to close the connection. It is safe to assume that the data associated with the connection should remain available during processing, but memory may be freed as soon as the connection is closed. But how can I properly create / destroy data? Assuming I use class es and associate the callback with member functions, should I create a class with new and call delete this; once the processing is complete or is there a better way?

+3
source share
1 answer

But how can I properly create / destroy data?

Use shared_ptr .

Assuming I use classes and associate a callback with member functions, should I create a class using new and call delete this; once the processing is complete or is there a better way?

Make your class an inheritance from enable_shared_from_this , instantiate your classes using make_shared , and when you bind your callbacks, bind them to shared_from_this() instead of this . Destruction of your instances will be performed automatically when they exit the last area where they are needed.

+1
source

Source: https://habr.com/ru/post/1266385/


All Articles