如何对Boost图中std::shared_ptr封装的图属性进行深拷贝?
核心问题
你需要对schGraphProps类中std::shared_ptr<vertexProps> _vertexPtr进行深拷贝,而shared_ptr默认仅拷贝指针(浅拷贝),不会复制指向的对象本身,因此需要手动创建新的vertexProps实例并让目标shared_ptr指向它。
具体实现步骤
1. 确保vertexProps具备正确的拷贝构造
首先为vertexProps添加显式拷贝构造函数,保证其成员属性能被正确拷贝(注意:如果_subGraph/_graph指向的图也需要深拷贝,需额外扩展逻辑):
class vertexProps { public: // 原构造函数保留 explicit vertexProps(const std::string *moduleName = nullptr, const std::string *name = nullptr, long refPtr = 0 ) : _refPtr(refPtr) { _moduleName = moduleName ? *moduleName : ""; _name = name ? *name : ""; }; // 显式拷贝构造函数 vertexProps(const vertexProps& other) : _moduleName(other._moduleName), _name(other._name), _subGraph(other._subGraph), // 若需深拷贝图,此处需替换为新创建的BGType实例 _graph(other._graph), _refPtr(other._refPtr) {} std::string _moduleName; std::string _name; BGType *_subGraph = nullptr; BGType *_graph = nullptr; long _refPtr; // 补充原代码中遗漏的成员变量 };
2. 在DeepCopyOfBG中处理_vertexPtr的深拷贝
修改DeepCopyOfBG函数,添加对_vertexPtr的深拷贝逻辑:
void DeepCopyOfBG(BGType *bGraph, BGType *oldBg) { boost::copy_graph( *bGraph, *oldBg, boost::vertex_copy(CustomVertexCopy{*bGraph, *oldBg}).edge_copy(CustomEdgeCopy{*bGraph, *oldBg})); boost::get_property(*oldBg) = boost::get_property(*bGraph); // 深拷贝_altNames映射 for (auto entry : (*bGraph)[boost::graph_bundle]._altNames) { std::vector<std::string> deepCopyValues(entry.second.begin(), entry.second.end()); (*oldBg)[boost::graph_bundle]._altNames[entry.first] = deepCopyValues; } // 深拷贝_modSymbol映射 for (auto entry : (*bGraph)[boost::graph_bundle]._modSymbol) { (*oldBg)[boost::graph_bundle]._modSymbol[entry.first] = entry.second; } // 深拷贝_vertexPtr指向的vertexProps对象 auto& src_graph_props = (*bGraph)[boost::graph_bundle]; auto& dst_graph_props = (*oldBg)[boost::graph_bundle]; if (src_graph_props._vertexPtr) { // 创建新的vertexProps实例,拷贝源对象的所有属性 auto new_vertex = std::make_shared<vertexProps>(*src_graph_props._vertexPtr); // 可选:如果需要深拷贝_subGraph/_graph指向的图,添加以下递归逻辑 // if (new_vertex->_subGraph) { // new_vertex->_subGraph = new BGType; // DeepCopyOfBG(new_vertex->_subGraph, new_vertex->_subGraph); // } // if (new_vertex->_graph) { // new_vertex->_graph = new BGType; // DeepCopyOfBG(new_vertex->_graph, new_vertex->_graph); // } dst_graph_props._vertexPtr = new_vertex; } else { dst_graph_props._vertexPtr = nullptr; } }
补充说明
- 如果
vertexProps中的_subGraph或_graph指针指向的Boost图也需要深拷贝,需在拷贝构造函数或DeepCopyOfBG中添加递归拷贝逻辑,否则这些指针会保持浅拷贝(指向原对象)。 - 使用
std::make_shared创建新的vertexProps实例,能保证内存管理的安全性,避免手动new/delete带来的内存泄漏风险。
内容的提问来源于stack exchange,提问作者tushar
相关产品推荐
相关产品推荐

