在 lambda 函数中使用自动自(shared_from_this()) 变量的原因是什么?

What's the reason of using auto self(shared_from_this()) variable in lambda function?

本文关键字:变量 是什么 this shared 函数 lambda from      更新时间:2023-10-16

我阅读了boost asio http服务器示例代码(请参阅 http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/example/cpp11/http/server/connection.cpp),发现auto self(shared_from_this());变量已在捕获范围内使用([this, self])。但是 self 变量没有在 lambda 函数中使用。那么这样做有什么好处呢?

这样做

是为了确保connection对象比异步操作更持久:只要 lambda 处于活动状态(即异步操作正在进行中),connection 实例也处于活动状态。