C++ - 删除包含向量的结构向量是否会导致内存泄漏
C++ - Will deleting a vector of structs that contain vectors cause memory leaks?
我正在构建一个游戏,并有一个称为精灵的对象向量。
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 struct
与class
没有太大区别,只是它默认public
其成员的可见性。
只有当
SpriteChild 的析构函数未正确定义时,它才会导致泄漏(即SpriteChild的析构函数需要删除任何动态分配的记忆)。
删除两次可能会导致崩溃。
但是,仅删除使用 new 成功分配的对象不应导致内存泄漏。
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 故意泄漏std::向量的内存
- 带有Valgrind的C 的向量分配中的内存泄漏
- C 内存泄漏是由结构向量引起的
- 分配包含stl向量的结构时内存泄漏
- 将指针push_back到指针向量中是内存泄漏吗?
- 指向对象的指针向量 - 内存泄漏
- C++ - 删除包含向量的结构向量是否会导致内存泄漏
- 使用字符串映射的向量时可能会发生内存泄漏C++
- 使用类向量时会遇到内存泄漏吗?(C++)
- 内存泄漏C++指针向量
- 使用复杂的数据结构(向量数组的数组数组)时内存泄漏
- 已分配结构包含向量的内存泄漏
- 共享指针和内存泄漏的C++11向量
- c++中的内存泄漏:循环中的向量函数
- 为什么valgrind显示泄漏,即使包含动态分配对象的向量被释放
- 不清楚的内存泄漏与向量,c++,当调用退出
- 内存泄漏,c++的向量回推
- 向量::p ush_back ( A * ) 产生泄漏