我有两门课:
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
和查找目标实体的部分是成功的,但是它在RemoveEntity
的delete *
指令处崩溃(我通过在每行代码后面添加日志指令来检查这些内容)。这是我用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")
我怎么能纠正这个问题呢?在
创建一个拥有C++ ^ {< CD1>}的Python对象。一生都在管理它。在
^{pr2}$这里,我们将由^ {CD2>}包的C++对象传递给由{{CD3}}包的C++对象。C++对象存储在^ {CD4}}的向量中。在
这将删除您在上面添加的
Entity
。但是,test_e
类*仍然认为它拥有Entity
,因为它无法被告知您已经失去了所有权。但现在它拥有一个无效指针。在崩溃发生在删除,因为C++没有管理内存Python。它不使用C++堆。在
<>你需要在C++代码中有一个更为完善的所有权和寿命管理设计。永远不要^ { CD8}}您没有{^ {CD9}},Python实例中的C++代码永远不会^ {< CD9> },{{CD1}}。在相关问题 更多 >
编程相关推荐