在 lambda 函数中使用 auto self(shared_from_this()) 变量的原因是啥?

Posted

技术标签:

【中文标题】在 lambda 函数中使用 auto self(shared_from_this()) 变量的原因是啥?【英文标题】:What's the reason of using auto self(shared_from_this()) variable in lambda function?在 lambda 函数中使用 auto self(shared_from_this()) 变量的原因是什么? 【发布时间】:2013-10-22 11:27:49 【问题描述】:

我阅读了 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])中使用。但是在 lambda 函数中没有使用 self 变量。那么这样做有什么好处呢?

【问题讨论】:

【参考方案1】:

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

【讨论】:

很好的解释。您是否可以对***.com/q/29613178/836097 的后续问题发表意见? 能否解释一下为什么auto self(shared_from_this()); 没有在client 示例中使用(而server 使用了那个)? @SAMPro 因为在客户端示例中,没有任何东西可以通过shared_ptr 进行管理。该示例中的client 实例具有自动存储功能。

以上是关于在 lambda 函数中使用 auto self(shared_from_this()) 变量的原因是啥?的主要内容,如果未能解决你的问题,请参考以下文章

lambda在绑定槽函数时的应用

Auto-PEP8 通过将我的 lambda 转换为 def 函数来添加行,我如何禁用这种特定的自动格式?

在 C++11 中用“auto”推导时 lambda 的类型是啥?

为啥 lambda auto& 参数选择 const 重载?

错误:在 lambda 参数声明中使用 'auto' 仅适用于 -std=c++1y 或 -std=gnu++1y [-Werror]

如何将 Numpy Eig 与 Python Lambda 函数一起使用?