代码之家  ›  专栏  ›  技术社区  ›  Paul Belanger

lambda捕获值是否可以优化?

  •  2
  • Paul Belanger  · 技术社区  · 6 年前

    我目前正在为一个项目使用boost::asio,并且必须向远程端点发送缓冲区。我当前发送数据的算法如下:

    void send_the_data(DataElement const& data)
    {
        auto databuf = make_shared<std::vector<uint8_t>>(data.to_bytes());
    
        // lambda object holds a reference to the data to prevent early destruction. 
        asio::async_write(this->sock,
            asio::buffer(databuf),
            transfer_all(),
            [this, databuf](size_t bt, boost::system::error_code const& ec)
        {
            if(ec) this->handle_error(ec);
            else this->do_the_next_thing();
    
            assert(bt = databuf->size());
            // the destructor of this lambda should clean up the data buffer here,
            // after it has been handled. 
        });
    
    }
    

    我的逻辑是,共享ptr的lambda捕获将防止它在 async_write 处理完毕,然后在处理程序执行后正确清理缓冲区。

    但是,我很好奇,如果lambda主体中没有引用变量,那么主要编译器或标准是否允许省略变量的捕获,这将导致未定义的行为(因为可能访问 或者如果标准保证所有捕获的值都不会被忽略。

    1 回复  |  直到 6 年前
        1
  •  5
  •   Michael Kenzel    6 年前

    [expr.prim.lambda] §2 理论上允许编译器优化闭包类型,这种优化只允许在 好像规则一样 . 因此编译器可以从闭包类型中优化未引用的数据,但它仍然必须产生与相应成员的构造/销毁相关联的任何副作用。

    [expr.prim.lambda] §10 指定为每个显式捕获创建闭包类型的成员。 [expr.prim.lambda] §15 指定如何初始化。基于此,我认为编译器是 允许优化您的 shared_ptr .