【问题标题】:Delete and remove a pointer from a list从列表中删除和移除指针
【发布时间】:2021-11-15 18:43:12
【问题描述】:

我有这段代码(它是复制错误的代码的 smol 版本),它给出了某种内存错误。 idk 请帮我解决它。它删除了对象,因此只剩下 nullptr。我知道为什么,但它不想从列表中删除指针。

#include <iostream>
#include <list>
// casual include

在这里我创建了一个类,它是我所有其他类的基础

class Object // a virtual class
{
public:
    bool needs_delete = false;

    virtual void tick() {}
    virtual void render() {}
};

一个继承自我之前创建的 Object 类的播放器类

class Player : public Object
{
public:
    float x, y; // <-- just look at da code dont read dis

    Player(float x, float y) : // i initialize the "x" & "y" with the x & y the user has set in the constructor
        x(x), y(y)
    {}

    void tick() override // just look at the code
    {
        x++;
        if (x > 10000)
        {
            needs_delete = true;
        }
    }

    void render() override // just look at the code
    {
        // nothing...
    }
};

只是主要功能。在这一点上,我只是在写文字,因为 stackoverflow 不会让我发布这段持续的抑郁症。请帮助:)

int main()
{
    std::list<Object*>* myObjs = new std::list<Object*>; // a list that will contain the objects

    for (int i = 0; i < 1000; i++) // i create 1k player just for testing
    {
        myObjs->push_back(new Player(i, 0));
    }

    while (true)
    {
        if (myObjs->size() == 0) // if there are no objects i just break out of the loop
            break;
        
        for (Object* obj : *myObjs) // update the objects
        {
            obj->tick();
            obj->render();

            // some other stuff
        }


        // DA PART I HAVE NO IDEA HOW TO DO
        // pls help cuz i suck

        for (Object* obj : *myObjs) // help pls :)
        {
            // baisicly here i want to delete the object and remove it from the list
            if (obj->needs_delete)
            {
                std::cout << "deleted object\n";
                delete obj;
                myObjs->remove(obj);
            }
        }

    }
}

【问题讨论】:

  • 请创建一个单件 MRE,minimal reproducible example。 IE。尝试在一个可复制粘贴的代码文件中演示您的问题。如果你尽可能地缩小它并添加一些你观察到的描述,那么 SO 不会阻止你发布你的 MRE。
  • 你试过remove_if吗?它也适用于 lambda。
  • 代码实际上存在多个问题。您不应该在遍历列表时从列表中删除,当您调用 delete obj 时,您将 obj 设置为 nullptr,因此您不能调用 myObjs->remove(nullptr)
  • 问题是您在迭代列表时要从列表中删除元素。
  • @Po1nt delete obj 不会修改 obj

标签: c++ list pointers memory


【解决方案1】:

怎么样:

myObjs->remove_if([](auto& pObj)
{
    if ( pObj->needs_delete )
    {
        delete pObj;
        return true;
    }
    else 
        return false;
});

【讨论】:

    猜你喜欢
    • 2017-04-05
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2013-11-15
    相关资源
    最近更新 更多