gpt4 book ai didi

c++ - std::list 元素删除引起麻烦

转载 作者:行者123 更新时间:2023-11-30 03:04:12 24 4
gpt4 key购买 nike

我已经尝试调试了将近半天,但我似乎找不到问题所在。最有可能导致问题的是这种方法:

//[datamember]    
std::list<Projectile*> m_Projectiles_l;

//[predicate]
bool removeDeads(Projectile* pProj) {
return !(pProj->isAlive());
}

//[the method I think might be causing the problem]
void ProjectileList::KillDeadProjectiles()
{
std::list<Projectile*>::iterator it;
it = std::remove_if(m_Projectiles_l.begin(), m_Projectiles_l.end(), &removeDeads);

if (it != m_Projectiles_l.end())
{
std::list<Projectile*>::iterator itDelete;
for (itDelete = it; itDelete != m_Projectiles_l.end(); ++itDelete) {
delete (*itDelete);
}
m_Projectiles_l.erase(it, m_Projectiles_l.end());
}
}

VS2010 中断错误:

Unhandled exception at 0x00389844 in PsychoBots.exe: 0xC0000005: Access violation reading location 0xfeeeff3a.

Breaking 把我带到了这条线:

void ProjectileList::DoPhysicsStuff(const InputState& refInputState)
{
KillDeadProjectiles();

std::list<Projectile*>::iterator it;
for (it = m_Projectiles_l.begin(); it != m_Projectiles_l.end(); ++it) {
/*[THIS line]*/(*it)->DoPhysicsStuff(refInputState);
}
}

我的发现:

It gives a problem when: there are more than 2 elements in the list, and a "projectile that has been added to the list earlier than a projectile that has been added later on" is getting removed with this method.

It gives no problems when: There is only one element in the list OR All the elements are getting removed at the same time.

任何人都可以看到其中的任何错误吗?

如果您需要更多代码,请发表评论,我现在尽量保持小尺寸。

最佳答案

您不能依赖 remove_if 返回的迭代器之外的容器内容。这意味着如果您想管理容器中的动态内存,您将不得不采用不同的方法。简单的方法是存储 shared_ptr 对象而不是原始指针。然后你可以只使用 remove-erase 习惯用法,所有的东西都会被清理干净。否则,您需要自己仔细编写删除机制,而不是使用 remove_if

关于c++ - std::list 元素删除引起麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8821772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com