What's the best way of ensuring valid object lifespan when using Boost.Asio?

前端 未结 2 1037
礼貌的吻别
礼貌的吻别 2021-02-07 17:15

Been playing a lot with Boost.Asio of late. I like the library a lot since it offers a fantastic way to squeeze performance out of today\'s multicore systems.

A questio

2条回答
  •  误落风尘
    2021-02-07 17:57

    Using boost::enable_shared_from_this is pretty much the way to do it. Additionally, look at using boost::weak_ptr if you need references to the object that should not preserve the object if they are the only references which remain.

    A good example of using weak_ptr: I use enable_shared_from_this in my socket class which utilizes boost::asio. The boost::asio framework is the only thing that stores persistent references to the object, via read and write handlers. Thus, when the socket's destructor is called, I know that the socket is closed and I can "do stuff" in a handler to clean up for that closed socket. The application which uses the socket only has a weak_ptr reference to it, which it promotes to a shared_ptr when it wants to work with the socket (usually to write to it). That promotion can be checked for failure in case the socket went away, although the socket's close handler usually cleans up all the weak_ptr references appropriately before that even happens.

提交回复
热议问题