我正在尝试使用 Visual Leak Detector 查找内存泄漏。
它告诉我 m_neighbors.push_back(ent);
导致泄漏。
(简短调用堆栈 = NeighborCalculatorDummy -> foreach -> 列表 -> 分配)
我将其用作 NeighborCalculatorDummy<Entity *>
,所以 pushback 应该只在列表中插入指针而不进行任何分配。
所有通过 addEntity 指向实体的指针都在代码的其他地方被删除...
push_back
怎么可能导致泄漏?
template <typename entity_type>
class NeighborCalculatorDummy
{
public:
inline void addEntity(const entity_type & entity)
{
m_entities.push_back(entity);
}
void calculateNeighbors(const vector_type & position, flt32 radius)
{
flt32 rSq = radius*radius;
m_neighbors.clear();
std::for_each(m_entities.begin(), m_entities.end(), [&](entity_type ent){
if(lengthSq(ent->getPosition() - position) <= rSq)
m_neighbors.push_back(ent);
});
}
private:
std::vector<entity_type> m_entities;
std::list<entity_type> m_neighbors;
};
编辑
这是 NeighborCalculator 的代码
//#1
std::list<Vehicle *> vehicles;
vehicles.push_back(new Vehicle);
vehicles.push_back(new Vehicle);
vehicles.push_back(new Vehicle);
//#2
NeighborCalculatorDummy<Vehicle *> neighborCalculator = new NeighborCalculatorDummy<Vehicle *>();
std::for_each(vehicles.begin(), vehicles.end(), [&](Vehicle * vehicle){
neighborCalculator->addEntity(vehicle);
});
//#3 impl of addEntity
template <typename entity_type>
void NeighborCalculatorDummy<entity_type>::addEntity(const entity_type & entity)
{
...
m_entities.push_back(entity); //m_entities is - std::vector<Vehicle *>
}
//#4 end of program
delete neighborCalculator;
std::for_each(vehicles.begin(), vehicles.end(), [&](Vehicle * vehicle){
delete vehicle;
});
最佳答案
在我看来entity_type
是一个指针(从 for_each lambda 判断)。
你可能想用
NeighborCalculatorDummy<SomeEntity>
代替
NeighborCalculatorDummy<SomeEntity*>
在您代码的其他地方(未显示)
当然,lambda 的拼写会有所不同:
[&](const entity_type& ent){
if(lengthSq(ent.getPosition() - position) <= rSq)
m_neighbors.push_back(ent);
}
也许还有更多假设 entity_type 类型需要取消引用的相似点。
或者,你可以使用
-
vector<std::shared_ptr<entity_type> >
相反 - 提升指针容器
当您的实体是多态类型或不可复制/可移动时,这些可能更合适。但是,更改您的代码也可能需要更多工作
关于c++ - push_backing 到指针列表中导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7661347/