Fix memory leak in step 7

This commit is contained in:
Love 2024-09-11 16:48:46 +02:00
parent dbfbb27044
commit c9be0f2d2f
9 changed files with 40 additions and 5 deletions

View File

@ -22,6 +22,10 @@ GameState::GameState(int numberOfRobots) {
}
GameState::~GameState(){
clearUnits();
}
void GameState::clearUnits(){
for (Unit *unit: units)
delete unit;
units.clear();
@ -63,6 +67,23 @@ void GameState::updateCrashes() {
}
}
GameState &GameState::operator=(const GameState &other) {
if (this == &other)
return *this;
clearUnits();
for (const Unit *const unit : other.units)
units.push_back(unit->clone());
hero = other.hero;
return *this;
}
GameState::GameState(const GameState &other) : hero(other.hero) {
clearUnits();
for (const Unit *const unit : other.units)
units.push_back(unit->clone());
}
int GameState::countToBeJunked() const {
int numberDestroyed = 0;
for (const Unit *const unit: units)

View File

@ -27,7 +27,8 @@ public:
~GameState();
GameState &operator=(const GameState &other);
GameState(const GameState &other);
/*
* Clear and redraw entire playing field
*/
@ -84,6 +85,7 @@ private:
// private helpers
bool isEmpty(const Unit& unit) const;
void clearUnits();
};

View File

@ -14,3 +14,6 @@ void Hero::draw(QGraphicsScene *scene) const {
UNIT_WIDTH, UNIT_HEIGHT), Qt::NoPen, QBrush(HERO_COLOR));
}
Unit *Hero::clone() const {
return new Hero(*this);
}

View File

@ -12,11 +12,12 @@
class Hero : public Unit {
public:
Unit *clone() const override;
/*
* Draws this hero onto the given QGraphicsScene.
*/
void draw(QGraphicsScene *scene) const;
void draw(QGraphicsScene *scene) const override;
};

View File

@ -19,3 +19,7 @@ bool Junk::isAlive() const { return false; }
bool Junk::isToBeJunked() const { return false; }
void Junk::doCrash() {}
void Junk::moveTowards(const Point &) {}
Unit *Junk::clone() const {
return new Junk(*this);
}

View File

@ -12,7 +12,7 @@
class Junk : public Unit {
public:
Junk(const Point& p): Unit(p){}
Unit *clone() const override;
/*
* Draws this junk onto the given QGraphicsScene.
*/

View File

@ -25,4 +25,6 @@ void Robot::draw(QGraphicsScene *scene) const {
JUNK_RADIUS, JUNK_RADIUS), QPen(), QBrush(ROBOT_COLOR));
}
Unit *Robot::clone() const{
return new Robot(*this);
}

View File

@ -13,7 +13,7 @@ class Robot : public Unit {
bool toBeJunked = false;
public:
Unit* clone() const override;
/*
* did not crash yet
*/

View File

@ -28,6 +28,8 @@ public:
virtual ~Unit(){}
virtual Unit *clone() const = 0;
/*
* Return Point representation of Unit
*/