我想用Visual Leak Detector找到內存泄漏。 它顯示我m_neighbors.push_back(ent);
導致泄漏。push_backing到指針列表導致內存泄漏
(簡要調用堆棧= NeighborCalculatorDummy - >的foreach - >列表 - >分配)
我使用它作爲NeighborCalculatorDummy<Entity *>
,所以推回應該只在插入列表指針沒有任何分配。 所有通過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'的類型以及如何使用NeighborCalculatorDummy(是否被銷燬?)如果泄漏的內存是在push_back調用中獲取的,那麼似乎表明該清單沒有被正確銷燬。 –
CRT內存泄漏檢測儀是否顯示相同的泄漏? –