我正在优化当前的CLI项目。在查看代码和调试时,我发现我没有在类中释放一些动态分配的内存。这里是我的代码看起来是:尝试删除动态分配的对象会导致运行时崩溃
#include "Laser.h"
Laser::Laser(int x, int y)
{
initCoord = new Coordinate;
initCoord->x = x;
initCoord->y = y;
icon = '~';
}
char Laser::getIcon() const { return icon; }
Coordinate* Laser::getCoord() { return initCoord; }
void Laser::move()
{
++initCoord->x;
}
我已经试过
“Coordinates.h”
#pragma once
#include <Windows.h>
#define LENGTH 40
#define WIDTH 15
struct Coordinate
{
int x = 1;
int y = 1;
};
“Laser.h”
#pragma once
#include "Coordinates.h"
class Laser
{
private:
Coordinate* initCoord;
char icon;
public:
Laser(int x, int y);
char getIcon() const;
Coordinate* getCoord();
void move();
};
“Laser.cpp”添加一个析构函数(当然首先在头文件中声明它),清理分配给initCoord
的内存,这看起来像这:
Laser::~Laser()
{
if(initCoord != nullpr) delete initCoord;
}
添加后,它导致运行时错误。 “ProgramName.exe已停止工作...”此类的对象存储在一个简单的向量中,该向量在程序一次被清除。问题在于碰撞发生在它达到lasers.clear()
线之前。我真的不知道为什么这个崩溃发生,并会感谢一些帮助。谢谢! :)
您违反了三/五规则。 – Rakete1111
我很好奇为什么你甚至只用2个'int'成员动态地分配'struct'。在这种情况下,将其存储为“普通”成员应该更好。 (如果你真的需要一个指针,使用智能指针几乎总是一个更好的解决方案) – UnholySheep
我不确定,但没有代码“++ initCoord-> x”改变你的指针“x”字段? – ElChupacabra