【发布时间】:2020-12-23 07:19:00
【问题描述】:
我正在尝试找出如何删除我的 Block 类的子级。我试图用原始指针来做。我不知道为什么,但它没有工作。我收到了标量删除错误。我现在尝试用 std::shared_ptr 来做这件事。我也没有工作。我正在删除孩子:
void Block::remove(Block* block)
{
std::shared_ptr<Block> ptr(block);
auto it = std::find(children.begin(), children.end(), ptr);
if (it != children.end())
{
*it = NULL;
children.erase(it);
}
}
块删除器是:
Block::~Block()
{
for (auto& child : this->children)
{
child = NULL;
}
if (!this->children.empty())
this->children.clear();
}
根据调试过程,找到ptr变量,然后删除。在删除所有内容时都运行良好,直到最后一行,我得到了标量删除错误。仅作记录:children 变量的类型为 std::vector<std::shared_ptr<Block>>。
编辑: 完整代码在这里:https://github.com/DragonGamesStudios/Ages-of-Life。所有的block函数都定义在AOLGuiLibrary/source/Block.cpp中
【问题讨论】:
-
从作为参数传入的任何指针创建共享指针可能属于“坏主意”(带有大写字母),但要获得真正的帮助,您应该提供minimal reproducible example。跨度>
-
你不需要显式的析构函数来销毁
std::vector<std::shared_ptr<Block>>。编译器生成的那个会做正确的事。 -
@JaMiT 为什么这是个坏主意?
-
因为您的代码会在
remove()的末尾有效地调用delete block,@Sherlock。 -
A minimal reproducible example 不应依赖外部网站的链接
标签: c++ oop shared-ptr