删除boost::python公开的std::vector中的指针

2024-09-30 10:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两门课:

typedef std::vector<Entity *> EntityPtrVector;

class A
{
private:
    EntityPtrVector entity_vector;

public:
    void AddEntity(Entity *);
    void RemoveEntity(std::string);
};

class Entity
{
private:
    std::string name_;

public:
    Entity();
    Entity(std::string);

    std::string GetName(void) const { return name_; }
    void SetName(const std::string& name) { name_ = name; }
};

我用boost::python将它们公开如下:

^{pr2}$

AddEntity和{}的实现是:

void Game::AddEntity(Entity *E)
{
    entity_vector.push_back(E);
}

void Game::RemoveEntity(std::string entity_name)
{
    EntityPtrVector::iterator entity_ptr;

    // Find the entity with the input name
    for(entity_ptr = entity_vector.begin(); entity_ptr != entity_vector.end(); ++entity_ptr)
    {
        if((*entity_ptr)->GetName() == entity_name)
        {
            break;
        }
    }
    // Remove the target entity
    if(entity_ptr != entity_vector.end())
    {
        delete *entity_ptr;
        entity_vector.erase(entity_ptr);
    }
}

我已经检查过它在C++下工作,而不暴露于Python。在python中,AddEntity和查找目标实体的部分是成功的,但是它在RemoveEntitydelete *指令处崩溃(我通过在每行代码后面添加日志指令来检查这些内容)。这是我用python编写的测试代码:

import my_lib

test_a = my_lib.A("Test A")
test_e = my_lib.Entity("Test Entity")

test_a.AddEntity(test_e)
test_a.RemoveEntity("Test Entity")

我怎么能纠正这个问题呢?在


Tags: thenameteststringmylibentitystd
1条回答
网友
1楼 · 发布于 2024-09-30 10:30:58
test_e = my_lib.Entity("Test Entity")

创建一个拥有C++ ^ {< CD1>}的Python对象。一生都在管理它。在

^{pr2}$

这里,我们将由^ {CD2>}包的C++对象传递给由{{CD3}}包的C++对象。C++对象存储在^ {CD4}}的向量中。在

test_a.RemoveEntity("Test Entity")

这将删除您在上面添加的Entity。但是,test_e类*仍然认为它拥有Entity,因为它无法被告知您已经失去了所有权。但现在它拥有一个无效指针。在

崩溃发生在删除,因为C++没有管理内存Python。它不使用C++堆。在

<>你需要在C++代码中有一个更为完善的所有权和寿命管理设计。永远不要^ { CD8}}您没有{^ {CD9}},Python实例中的C++代码永远不会^ {< CD9> },{{CD1}}。在

相关问题 更多 >

    热门问题