【问题标题】:C++17 copy constructor, deep copy on std::unordered_mapC++17 复制构造函数,std::unordered_map 上的深拷贝
【发布时间】:2018-11-04 12:30:56
【问题描述】:

我在实现对我的预制子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 的 copy ctor。
  • 你指的是哪个指针?你的意思是 std::unordered_map as PrefabActor * ?
  • 我的意思是,为什么不std::unordered_map&lt;unsigned, PrefabActor&gt;

标签: c++ recursion c++17 deep-copy unordered-map


【解决方案1】:

您必须手动复制条目:

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

当然,你也需要改变孩子的父对象。

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

【讨论】:

  • for (auto it = rhs.child_actor_container.begin(); it != rhs.child_actor_container.end(); ++it , ++child_key) { PrefabActor * child_prefab = new PrefabActor(*(它->第二)); child_prefab->SetParentPointer(this); child_actor_container.emplace(child_key, child_prefab); } 这样可以吗?
  • 什么是child_key?我以为你想要一个深度克隆。如果您有其他 ID,那么是的,您必须将此代码调整为您未在问题中提出的内容。
  • child_key 只是一个无符号值,即 child_prefab_actor_key
  • 哦,好的。正如我所说,您需要根据您跟踪和识别对象的具体情况调整代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 2012-11-11
相关资源
最近更新 更多