c++ - push_backing 到指针列表中导致内存泄漏

标签 c++ visual-studio list memory-leaks

我正在尝试使用 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/

相关文章:

c++ - 混淆后您的代码有多安全?

c++ - GCC6 中 undefined reference 为 'rt' ,'pthread' ,'stdc++fs'

c# - 从其他 C# 控制台应用程序运行 C# 控制台应用程序

Python 使用列表时输入错误

c - 如何将整数分配给c中的指针?

python - 如何将字典列表转换为元组列表?

c++ - 编译器隐式声明一个默认构造函数

javascript - QT 使用 addToJavaScriptWindowObject()

java - Visual Studio Java IDE

visual-studio - 您使用什么工具来计算 Visual Studio 项目中的源代码行数?