Push_backing 进入指针列表会导致内存泄漏
我正在尝试使用 Visual Leak Detector 查找内存泄漏。
它显示 m_neighbors.push_back(ent);
导致泄漏。
(brief callstack = NeighborCalculatorDummy -> foreach -> list -> allocate)
我将其用作 NeighborCalculatorDummy
,因此推回应该只在列表中插入指针而不进行任何分配。
所有指向通过 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;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我看来,entity_type 是一个指针(从 for_each lambda 来看)。
您可能想
使用而不是
在代码的其他地方
(未显示)当然,lambda 的拼写会有所不同:
并且可能有更多类似的地方假设实体类型需要取消引用。
或者,您可以使用
vector; >
而不是当您的实体是多态类型或不可复制/可移动时,这些可能更合适。但是,更改代码也可能需要更多工作
It seems to me that
entity_type
is a pointer (judging from the for_each lambda).You probably wanted to use
instead of
in some other place of your code (not shown)
Of course the lambda would then be spelled differently:
and perhaps more similar spots that assumed the type of entity_type needed dereferencing.
Alternatively, you could use
vector<std::shared_ptr<entity_type> >
insteadThese might be more appropriate when your entities are polymorphic types or non-copyables/movables. However, it is also likely more work to change you code around
通过这个定义,根据entity_type,代码是否会泄漏。
With this definition, depending on entity_type, the code will leak or not.
我在实体的父级中省略了虚拟析构函数。这就是为什么推回它会导致泄漏。
I have omitted virtual destructor in Entity's parent. That is why pushbacking it caused a leak.