我使用 boost::asio
已经有一段时间了,虽然我确实理解异步调用的概念,但我仍然对内存管理的含义有些困惑。在普通的同步 代码中,对象的生命周期是明确的。但请考虑类似于 daytime server 的情况。 :
可能有多个已被接受
的事件连接。每个连接现在从套接字发送和接收一些数据,在内部做一些工作,然后决定关闭连接。可以安全地假设与连接相关的数据需要在处理过程中保持可访问性,但一旦连接关闭,内存就会被释放。但是我怎样才能正确地实现数据的创建/销毁呢?假设我使用 class
es 并将回调绑定(bind)到成员函数,我是否应该使用 new
创建一个类并尽快调用 delete this;
处理完成还是有更好的方法?
最佳答案
But how can I implement the creation/destruction of the data correctly?
使用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?
使您的类继承自 enable_shared_from_this
,使用 make_shared
创建您的类的实例,并在绑定(bind)回调时将它们绑定(bind)到 shared_from_this()
而不是 this
。当实例超出最后需要它们的范围时,实例的销毁将自动完成。
关于c++ - 异步 C++ 代码中的内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24530771/