C++ - 删除包含向量的结构向量是否会导致内存泄漏

C++ - Will deleting a vector of structs that contain vectors cause memory leaks?

本文关键字:向量 泄漏 内存 是否 结构 删除 包含 C++      更新时间:2023-10-16

我正在构建一个游戏,并有一个称为精灵的对象向量。

struct Sprite
{
    SpriteType texture;     // The texture enumeration
    float x;                // The x position of the sprite
    float y;                // The y position of the sprite
    float xVel;             // The x velocity of the sprite
    float yVel;             // The y velocity of the sprite
    int imgBlockX;          // The x block in the image
    int imgBlockY;          // The y block in the image
    int numFrames;          // The number of frames in the sprite animation
    int curFrame;           // The current frame of animation
    int delay;              // The delay between frame switches
    int elapsed;            // The amount of time on this frame
    long lastTime;          // The last update time
    long curTime;           // The current update time
    bool loop;              // Does this animation loop?
    int lifespan;           // The max lifespan of the sprite
    int order;              // 0 for first 1 for last
    bool hasChildren;       // Is this a parent sprite?
    int maxSize;
    std::vector<SpriteChild> children;// The sprites that are linked to this one (die when this one dies)
};

正如你在底部看到的,它包含一个精灵子级的矢量本身。如果我从精灵矢量中删除一个元素,它会导致精灵矢量的内存泄漏还是得到了处理?

谢谢!

你的向量被分配为 Sprite 结构体的成员(它不是通过 new 分配的),所以当Sprite被删除时,它会自动清理。

当您通过new创建对象并且不delete它时,会出现内存泄漏。

无论您如何分配精灵向量,从中删除元素都会释放特定于该对象的向量children。相信SpriteChild不是指针类型的 typedef,而是结构名称。

如果你不搞砸SpriteChild,它会得到照顾.如果它在构造函数中分配了一些东西,请确保在析构函数中释放它。IIRC structclass没有太大区别,只是它默认public其成员的可见性。

只有当

SpriteChild 的析构函数未正确定义时,它才会导致泄漏(即SpriteChild的析构函数需要删除任何动态分配的记忆)。

删除两次可能会导致崩溃。

但是,仅删除使用 new 成功分配的对象不应导致内存泄漏。