简体   繁体   English

神秘的塞格。 故障

[英]The mysterious Seg. Fault

I have an Animals class, and from this specific animals are derived. 我有一个动物类,并从这个特定的动物派生。 I have a list of animals called mItems. 我有一个名为mItems的动物清单。 I want to see if my lions are hungry. 我想看看我的狮子是否饿了。 I have created virtual functions in my Animals class: 我在我的Animals类中创建了虚函数:

    virtual void IsLion() {return false;}
    virtual void IsHungry() {return false;}
    virtual void SetHungry(bool state) {}

In my Lion class I have extended these: 在我的Lion课程中,我扩展了这些:

    virtual void IsLion () {return true;}
    virtual void IsHungry () {return mHungry;}
    virtual void SetHungry () {mHungry = state;}

mHungry is a boolean member variable that will represent whether or not the lion is hungry. mHungry是一个布尔成员变量,用于表示狮子是否饥饿。

void CSafari::KillHungryLion()
{
for(list<CAnimals *>::iterator i=mItems.begin(); 
        i != mAnimals.end();  i++) 
    {
        if((*i)->IsLion())
        {
            if((*i)->IsHungry())
            {
              mItems.remove(*i);
              delete *i;
            }

         }
    }
 }

mItems is a list of pointers to CAnimal objects. mItems是指向CAnimal对象的指针列表。

If a Lion is hungry, he is dead! 如果狮子饿了,他就死定了! The problem I am having is endless segfaults. 我遇到的问题是无休止的段错误。 I cannot pinpoint where I am going wrong. 我无法确定我哪里出错了。 I have a function that is essentially equivalent to this that periodically updates the lions to being hungry, then I call this. 我有一个功能基本上相当于这个定期更新狮子饥饿的功能,然后我称之为。 It appears that it segfaults when I try to remove the items from mItems. 当我尝试从mItems中删除项目时,它似乎是段错误。 Any ideas? 有任何想法吗?

Once you remove the item from the list, the iterator pointing to that item is invalid. 从列表中删除项后,指向该项的迭代器无效。 See https://stackoverflow.com/a/3329962/1558890 . 请参阅https://stackoverflow.com/a/3329962/1558890 Calling i++ (or ++i ) on an invalid iterator is likely to lead to a segfault. 在无效迭代器上调用i++ (或++i )可能会导致段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM