异步C ++代码中的内存管理 [英] Memory management in asynchronous C++ code

查看:72
本文介绍了异步C ++代码中的内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用boost::asio已有一段时间了,虽然我确实理解了异步调用的概念,但我仍然对内存管理的含义感到困惑.在普通的 synchrous 代码中,对象的生存期很清楚.但是,请考虑类似于日间服务器:

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:

可能有多个活动连接已被accept建立.现在,每个连接都从套接字发送和接收一些数据,在内部做一些工作,然后决定关闭该连接.可以安全地假定与连接有关的数据在处理期间需要保持可访问性,但是只要关闭连接就可以释放内存.但是,如何正确实现数据的创建/销毁?假设我使用class es并将回调绑定到成员函数,我应该使用new创建一个类并在处理完成后立即调用delete this;还是有更好的方法?

There might be multiple active connections which have been accepted. 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 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?

推荐答案

但是如何正确实现数据的创建/销毁?

But how can I implement the creation/destruction of the data correctly?

使用shared_ptr.

假设我使用类并将回调函数绑定到成员函数,则应该使用new创建一个类并调用delete this;处理完成后,还是有更好的方法?

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创建类的实例,并在绑定回调时将它们绑定到shared_from_this()而不是this.当实例超出所需的最后一个范围时,销毁实例将自动完成.

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.

这篇关于异步C ++代码中的内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆