ZBLOG

两段代码: 第一个: sdbusplus::asio::getAllProperties( *crow::connections::systemBus, "xyz.openbmc_project.Raid.Manager", physicalPath, "xyz.openbmc_project.Raid.Physical", [physicalPath, storageId, inde...

第一段代码是正常的,而第二段代码会报错,是因为在lambda表达式中,使用了一个叫做drive的引用。当传递一个引用给lambda函数时,该引用必须保持有效。然而,在第二段代码中,drive引用的作用域在lambda之外,并且在getAllProperties完成之后就会销毁。

要解决这个问题,可以将drive作为一个副本传递给lambda函数,而不是作为引用。你可以通过在方括号内添加”= drive“来实现:

nlohmann::json drive = driver.emplace_back(nlohmann::json::object());

sdbusplus::asio::getAllProperties(
    *crow::connections::systemBus, "xyz.openbmc_project.Raid.Manager", physicalPath,
    "xyz.openbmc_project.Raid.Physical",
    [physicalPath, storageId,
        index, asyncResp, drive](const boost::system::error_code& ec,
                                const std::vector<std::pair<std::string, dbus::utility::DbusVariantType>>& propertiesList) {
        // lambda body
});

通过这样的方式,在lambda函数中使用的drive变量将成为一个拷贝,并且仍然可供lambda函数使用。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16434

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?