C++17复制构造函数,在std::unordereded_map上进行深度复制

C++17 copy constructor, deep copy on std::unordered_map

本文关键字:复制 map 深度 unordereded std C++17 构造函数      更新时间:2023-10-16

我在实现复制构造函数时遇到问题,该构造函数是在我的预制子参与者((上执行深度复制所必需的

std::unordered_map<unsigned, PrefabActor *> child_actor_container;

它也需要能够递归,因为里面的PrefabActor *可能有另一层子参与者容器。

类似这样的东西:

layer
1st   | 2nd   | 3rd
Enemy
Enemy_Body
Enemy_Head
Enemy_hand and etc
Enemy_Weapon

这里是我的实现:

class DataFileInfo
{
public:
DataFileInfo(std::string path, std::string filename );
DataFileInfo(const DataFileInfo & rhs);
virtual ~DataFileInfo();
// all other functions implemented here
private:
std::unordered_map<std::string, std::string> resource_info;
bool selection;
};
class PrefabActor : public DataFileInfo
{
public:
PrefabActor(std::string path, std::string filename , std::string object_type, PrefabActor * parent_actor = nullptr);
PrefabActor(const PrefabActor & rhs);
~PrefabActor();
// all other function like add component, add child actor function are here and work fine 
private:
unsigned child_prefab_actor_key; // the id key
PrefabActor* parent_prefab_actor; // pointer to the parent actor
std::unordered_map<ComponentType, Component*> m_ObjComponents; // contains a map of components like mesh, sprite, transform, collision, stats, etc.
//I need to be able to deep copy this unordered map container and be able to recursive deep copy 
std::unordered_map<unsigned, PrefabActor *> child_actor_container; // contains all the child actors
std::unordered_map<std::string, std::string> prefab_actor_tagging; // contains all the tagging
};

您必须手动复制条目:

PrefabActor(const PrefabActor & rhs)
{
for(const auto& entry:  rhs.child_actor_container)
{
child_actor_container[entry.first] = new PrefabActor(*entry.second);
}
}

当然,您还需要更改子对象的父对象。

您还应该指出谁拥有PrefabActor对象。这里可能存在内存泄漏。