第一段代码是正常的,而第二段代码会报错,是因为在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助手提供,问题来源于学员提问