From 1b49bc799b809366592af42934d3190cc07fca45 Mon Sep 17 00:00:00 2001 From: Love Billenius Date: Wed, 11 Sep 2024 17:29:35 +0200 Subject: [PATCH] Add move constructor/operator= --- src/GameState.cpp | 50 +++++++++++++++++++++++++++++++---------------- src/GameState.h | 6 ++++++ 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/src/GameState.cpp b/src/GameState.cpp index e727d49..13cf23e 100755 --- a/src/GameState.cpp +++ b/src/GameState.cpp @@ -31,6 +31,39 @@ void GameState::clearUnits(){ units.clear(); } +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()); +} + +GameState &GameState::operator=(GameState &&other) noexcept { + if (this == &other) + return *this; + clearUnits(); + + hero = std::move(other.hero); + units = std::move(other.units); + other.units.clear(); + + return *this; +} + +GameState::GameState(GameState &&other) noexcept : units(std::move(other.units)), hero(std::move(other.hero)) { + other.units.clear(); +} + void GameState::draw(QGraphicsScene *scene) const { scene->clear(); hero.draw(scene); @@ -67,23 +100,6 @@ 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) diff --git a/src/GameState.h b/src/GameState.h index f4a76f9..fca5f60 100755 --- a/src/GameState.h +++ b/src/GameState.h @@ -27,8 +27,14 @@ public: ~GameState(); + // Copy GameState &operator=(const GameState &other); GameState(const GameState &other); + + // Move + GameState &operator=(GameState &&other) noexcept; + GameState(GameState &&other) noexcept; + /* * Clear and redraw entire playing field */