繁体   English   中英

Memory 删除指针后泄漏

[英]Memory leak after deleting pointer

我有一个 memory 泄漏,我不知道为什么会发生。 请注意,我删除了大部分与问题无关的代码,并且大部分都在作业中给出,所以我只写了Tetrahedronadd_triangles(...) function:

class Geometry {
protected:
    unsigned int vao, vbo;
public:
    /* Generates 1 vertex buffer */
};

class Tetrahedron : public Geometry {
    std::vector<VertexData> vtxData;
    vec3 points[4];
public:
    Tetrahedron() : points { /* default points */ } { create(); }
    Tetrahedron(const vec3 p0, const vec3 p1, const vec3 p2, const vec3 p3) : points { p0, p1, p2, p3 } { create(); }
    void create() {
        /* Creates the 4 sides ans stores at vtxData */
        /* Passing the data to OpenGL */
    }
    void gen(std::vector<Tetrahedron*>& data, int stop_at = 0, float tend = 1, int depth = 0) {
        data.push_back(this);
        if (depth > stop_at) {
            return;
        }
        for (int i = 0; i < 4; i++) {
            /* calculate new points */
            (new Tetrahedron{ /* new points */ })->gen(data, stop_at, tend, depth + 1);
        }
    }
};

struct Object {
    Geometry* geometry;
public:
    /* Drawns and rotates the given geometry */
};

class Scene {
    std::vector<Object*> objects;
    std::vector<Tetrahedron*> thets;
public:
    void Build() {
        /* Setting up shaders, lights, materials, objects */
        add_triangles();
    }
    void add_triangles(float tend = 1) {
        for (unsigned int i = 0; i < objects.size(); i++) {
            delete objects[i];
        } std::vector<Object*>{}.swap(objects);

        for (unsigned int i = 0; i < thets.size(); i++) {
            delete thets[i];
        } std::vector<Tetrahedron*>{}.swap(thets);

        (new Tetrahedron{})->gen(thets, 1, tend);

        for (unsigned int i = 0; i < thets.size(); i++) {
            objects.push_back(new Object{ thets[i] });
        }
    }
    void Animate(float tstart, float tend) {
        /* ... */
        add_triangles(fabs(cosf(tend) * sinf(tend)) + 1);
        /* ... */
    }
    ~Scene() {
        for (unsigned int i = 0; i < objects.size(); i++) {
            delete objects[i];
        }
        for (unsigned int i = 0; i < thets.size(); i++) {
            delete thets[i];
        }
    }
};

由于某种原因,当我不将四面体存储在单独的向量中而只是在对象的析构函数中删除它们时,就会发生 memory 泄漏:

~Object() { delete geometry; }

如果它应该与在add_triangles(...) function 中编写的 for 循环中删除它们相同,它为什么会泄漏? - 我使用VS2019编译它。

纠正自己:

  • 这段代码实际上不会泄漏,它会单独删除四面体。
  • 如果我想让 Object 删除它的四面体“几何”,它就会泄漏。

Tetrahedron 继承自 Geometry,您正在从指向 Geometry object 的指针中删除。 没有调用 Tetrahedron 的析构函数,因为您没有将 Geometry 的析构函数定义为虚拟的。

在 Geometry 中添加一个虚拟析构函数以允许在这种情况下调用 Tetrahedron 的析构函数。

class Geometry {
protected:
    // ...
public:
    virtual ~Geometry() {} // <= Virtual destructor
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM