【问题标题】: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 变量。那么这样做有什么好处呢?

【问题讨论】:

    标签: c++ boost c++11 lambda boost-asio


    【解决方案1】:

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

    【讨论】:

    • 很好的解释。您是否可以对stackoverflow.com/q/29613178/836097 的后续问题发表意见?
    • 能否解释一下为什么auto self(shared_from_this()); 没有在client 示例中使用(而server 使用了那个)?
    • @SAMPro 因为在客户端示例中,没有任何东西可以通过shared_ptr 进行管理。该示例中的client 实例具有自动存储功能。
    猜你喜欢
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2020-08-07
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多