C++修改drop_location未同步prod_config:拷贝位置及直接操作方案
问题原因
拷贝发生的位置分为两处:
- 核心拷贝发生在
getDropLocationByName函数的最后一行drop_location_out = *it:你业务代码中声明的drop_location是独立的局部值对象,函数只是把prod_config中匹配到的dropLocation对象的全量内容拷贝到了这个局部对象里,二者是完全独立的内存实例,修改局部对象自然不会影响prod_config中的原对象。 - 非核心的额外拷贝:
std::find_if的Lambda参数用了值传递auto drop_location,遍历每一个元素时都会触发一次临时拷贝,虽然不影响核心逻辑,但属于不必要的性能损耗。
解决方法
直接修改getDropLocationByName的返回值为目标对象的引用,避免全量拷贝,即可直接操作prod_config中的原始对象:
修改后的函数实现
// 函数直接返回匹配到的dropLocation对象的引用 models::dropLocation_t& getDropLocationByName(models::prod_t& prod_config, const std::string& query_drop_location_name) { auto& drop_locations = prod_config.dropLocations; auto it = std::find_if( drop_locations.begin(), drop_locations.end(), [&query_drop_location_name](const auto& drop_location) { // Lambda参数改为const引用,避免遍历过程的临时拷贝 return drop_location.name == query_drop_location_name; }); if (it == drop_locations.end()) { std::stringstream ss; ss << "Drop location not found: " << query_drop_location_name; throw HTTP404Exception(ss.str()); } return *it; }
调整后的业务代码
auto prod_config = getProdConfig(nh); // 用引用接收返回值,直接指向prod_config中的原始对象 auto& drop_location = getDropLocationByName(prod_config, query_drop_location_name); // 此时修改的就是prod_config中的对应字段 drop_location.materials = materials;
补充说明
如果需要兼容常量查询场景,可以额外重载一个const版本的函数,返回const models::dropLocation_t&即可满足常量prod_config对象的查询需求。
内容的提问来源于stack exchange,提问作者Alexis Winters
相关产品推荐
相关产品推荐

