C++17复制构造函数,在std::unordereded_map上进行深度复制
C++17 copy constructor, deep copy on std::unordered_map
我在实现复制构造函数时遇到问题,该构造函数是在我的预制子参与者((上执行深度复制所必需的
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
对象。这里可能存在内存泄漏。
相关文章:
- std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数
- std::map insert && hyperload 导致复制
- C 将作为STD :: MAP复制到STD :: MAP的构造
- 为什么 std::map emplace 需要在 gcc 上有一个复制构造函数
- 如何将 std::map 值复制到非容器数组中
- C++ std::map 和 std::set 擦除复制值,从而使迭代器失效
- 关于从第二个存储值_ty2秒复制std :: Map Iterator的数据的问题
- 与 map 一起使用时复制构造函数常量错误
- 为什么map的元素不需要复制或移动构造函数,而vector需要?
- 如何在map中放置具有"deleted"复制ctor和赋值运算符的类?
- 将std::map复制/插入到boost::bimap中
- 使用 std::string 参数和不可移动/可复制参数构建 std::map
- <TiXmlDocument>在此卸载区域中使用的 map<shared_ptr、double> 不可按位复制
- std::map:插入密钥后,它是否可以复制和移动密钥
- 将包含类的类复制到 std::map
- C++ 将元素复制到 Map 中
- 如何将不可复制且不可移动的对象分配到std::map中
- 以vector、list或map为成员的类需要复制构造函数
- 在c++程序中将Map中的值复制到256x256数组
- 尝试将元素从Map复制到兼容优先级队列时出现无效堆错误