From 01862f6b40c0f8fbc0123f1ac5140a406c268251 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Tue, 10 Nov 2020 13:42:50 +0100 Subject: destructor and copy assignment operator --- labb4/GameState.cpp | 22 ++++++++++++++++++++++ labb4/GameState.h | 5 ++++- labb4/Junk.h | 1 + labb4/Robot.h | 1 + labb4/test-rule-of-three/main.cpp | 9 ++++++--- 5 files changed, 34 insertions(+), 4 deletions(-) diff --git a/labb4/GameState.cpp b/labb4/GameState.cpp index 6de11dd..47842a1 100644 --- a/labb4/GameState.cpp +++ b/labb4/GameState.cpp @@ -27,6 +27,28 @@ GameState::GameState(const GameState &other) { hero = other.hero; } +/* +*/ +GameState::~GameState() { + for (const auto &robot : robots) { + delete robot; + } + robots.clear(); +} + +GameState &GameState::operator=(const GameState &other) { + for (const auto &robot : robots) { + delete robot; + } + robots.clear(); + for (const auto &robot : other.robots) { + robots.push_back(robot->clone()); + } + hero = other.hero; + + return *this; +} + void GameState::draw(QGraphicsScene *scene) const { scene->clear(); for (int i = 0; i < robots.size(); i++) { diff --git a/labb4/GameState.h b/labb4/GameState.h index 331dcb7..ac749bb 100644 --- a/labb4/GameState.h +++ b/labb4/GameState.h @@ -21,7 +21,10 @@ class GameState { public: GameState(); GameState(int numberOfRobots); - GameState(const GameState &); + GameState(const GameState &other); + ~GameState(); + + GameState &operator=(const GameState &other); /* * Clear and redraw entire playing field diff --git a/labb4/Junk.h b/labb4/Junk.h index e8c028f..30659ab 100644 --- a/labb4/Junk.h +++ b/labb4/Junk.h @@ -13,6 +13,7 @@ class Junk : public Robot { public: Junk(); Junk(Robot c); + ~Junk() {} /* * Draws this junk onto the given QGraphicsScene. diff --git a/labb4/Robot.h b/labb4/Robot.h index cf05fab..6f68e9b 100644 --- a/labb4/Robot.h +++ b/labb4/Robot.h @@ -12,6 +12,7 @@ class Robot : public Unit { public: Robot(); + virtual ~Robot() {}; virtual void draw(QGraphicsScene* scene) const; virtual void moveTowards(const Unit& u); diff --git a/labb4/test-rule-of-three/main.cpp b/labb4/test-rule-of-three/main.cpp index ccef31a..6747169 100644 --- a/labb4/test-rule-of-three/main.cpp +++ b/labb4/test-rule-of-three/main.cpp @@ -35,14 +35,17 @@ GameState::GameState(const GameState &other) { GameState &GameState::operator=(const GameState &other) { std::cout << "=" << std::endl; - thing = other.thing; + delete thing; + thing = other.thing->clone(); return *this; } GameState::~GameState() { std::cout << "d gamestate" << std::endl; - delete thing; - thing = nullptr; + if (thing) { + delete thing; + thing = nullptr; + } } void GameState::switchThing() { -- cgit v1.2.1