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

标签 c++ recursion c++17 deep-copy 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);
    }
}

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

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

关于C++17 复制构造函数,std::unordered_map 上的深度复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53140850/

相关文章:

c++ - std::ranges::begin和std::begin之间有什么区别?

c++ - 运行方法并等待完成所有 for 循环 openmp

c++ - 懒惰的enable_if在工作时 sleep ?

c# - 重载时无限递归==

c++计算编译时间常数,同时防止整数常数溢出

c++ - 函数参数破坏的排序

java - 按深度加权的整数二叉树中的求和值

list - 为什么 Haskell 列表的 `++` 是递归实现的并且花费 O(n) 时间?

C++ 结构化绑定(bind)不适用于 bitset

c++ - 使用其类型而不是其实例调用不捕获