【发布时间】:2021-11-23 11:41:44
【问题描述】:
我有两个这样的功能。当我添加一个新对象时,一切都很好,但是如果我尝试添加一个已经在这个向量中的对象,应用程序就会关闭。从向量中删除后,我正在运行 unique_ptr 析构函数。如何解决?
void AddObject(GameObject* obj) {
objects().push_back(std::move(unique_ptr<GameObject>(obj)));
}
void DeleteObject(GameObject* obj) {
for (auto itr = objects().begin(); itr != objects().end(); ++itr) {
if ((*itr)->ID == obj->ID) {
objects().erase(std::move(itr));
itr->~unique_ptr();
}
}
}
【问题讨论】:
-
I am running the unique_ptr deconstructor after removing from a vector.为什么?而这一切是为了什么?std::move(unique_ptr<GameObject>(obj))使用emplace_back。 -
@TedKleinBergman 很抱歉,我需要在具有超类类型的向量中使用子类的字段和方法。我发现并有效的第一种实现方法是使用 unique_ptr。
-
@tkausl objects().emplace_back(std::move(unique_ptr
(obj)));没有帮助 -
objects().emplace_back(obj);. -
But even if you just add the same object more than 2 times好吧,你不应该有多个拥有同一个对象的unique_ptrs。
标签: c++ vector unique-ptr