问题
I have been working with boost::asio
for a while now and while I do understand the concept of the asynchronous calls I am still somewhat befuddled by the memory management implications. In normal synchrous code the object lifetime is clear. But consider a scenario similar to the case of the daytime server:
There might be multiple active connections which have been accept
ed. Each connection now sends and receives some data from a socket, does some work internally and then decides to close the connection. It is safe to assume that the data related to the connection needs to stay accessible during the processing but the memory can be freed as soon as the connection is closed. But how can I implement the creation/destruction of the data correctly? Assuming that I use class
es and bind the callback to member functions, should I create a class using new
and call delete this;
as soon as the processing is done or is there a better way?
回答1:
But how can I implement the creation/destruction of the data correctly?
Use shared_ptr
.
Assuming that I use classes and bind the callback to member functions, should I create a class using new and call delete this; as soon as the processing is done or is there a better way?
Make your class inherit from enable_shared_from_this
, create instances of your classes using make_shared
, and when you bind your callbacks bind them to shared_from_this()
instead of this
. The destruction of your instances will be done automatically when they have gone out of the last scope where they are needed.
来源:https://stackoverflow.com/questions/24530771/memory-management-in-asynchronous-c-code