C++17 复制构造函数,深度复制 std::unordered_map

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

我在实现对我的预制子 actor 执行深度复制所需的复制构造函数时遇到问题,即

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

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

像这样:

 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);
    }
}

当然,children的parentobject当然也要改

您还应该指明谁拥有 PrefabActor object。这里可能存在内存泄漏。