summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGustav Sörnäs <gustav@sornas.net>2020-11-10 13:36:39 +0100
committerGustav Sörnäs <gustav@sornas.net>2020-11-10 13:36:39 +0100
commitb8da24cd224f9c4d793bb4bb9809b6b517f0ee38 (patch)
treee95240bf1d12aea575f0833dde632bb9a6c852a1
parent9cc46300dba5c1e53a26415507c4d08addfd89eb (diff)
downloadtddd86-b8da24cd224f9c4d793bb4bb9809b6b517f0ee38.tar.gz
test: rule of three
-rw-r--r--labb4/test-rule-of-three/main.cpp74
-rw-r--r--labb4/test-rule-of-three/main.hpp31
2 files changed, 105 insertions, 0 deletions
diff --git a/labb4/test-rule-of-three/main.cpp b/labb4/test-rule-of-three/main.cpp
new file mode 100644
index 0000000..ccef31a
--- /dev/null
+++ b/labb4/test-rule-of-three/main.cpp
@@ -0,0 +1,74 @@
+#include <iostream>
+#include "main.hpp"
+
+Base *DerivedA::clone() {
+ std::cout << "clone da" << std::endl;
+ return new DerivedA;
+}
+
+Base *DerivedB::clone() {
+ std::cout << "clone db" << std::endl;
+ return new DerivedB;
+}
+
+void Base::hello() {
+ std::cout << 0 << std::endl;
+}
+
+void DerivedA::hello() {
+ std::cout << 1 << std::endl;
+}
+
+void DerivedB::hello() {
+ std::cout << 2 << std::endl;
+}
+
+GameState::GameState() {
+ std::cout << "c" << std::endl;
+ thing = new DerivedA;
+}
+
+GameState::GameState(const GameState &other) {
+ std::cout << "cc" << std::endl;
+ thing = other.thing->clone();
+}
+
+GameState &GameState::operator=(const GameState &other) {
+ std::cout << "=" << std::endl;
+ thing = other.thing;
+ return *this;
+}
+
+GameState::~GameState() {
+ std::cout << "d gamestate" << std::endl;
+ delete thing;
+ thing = nullptr;
+}
+
+void GameState::switchThing() {
+ std::cout << "switch" << std::endl;
+ delete thing;
+ thing = new DerivedB;
+}
+
+int main(int argc, char *argv[]) {
+ GameState state;
+ state.thing->hello();
+ std::cout << std::endl;
+
+ GameState copy = state;
+ state.thing->hello();
+ copy.thing->hello();
+ std::cout << std::endl;
+
+ copy.switchThing();
+ state.thing->hello();
+ copy.thing->hello();
+ std::cout << std::endl;
+
+ state = copy;
+ state.thing->hello();
+ copy.thing->hello();
+
+ return 0;
+}
diff --git a/labb4/test-rule-of-three/main.hpp b/labb4/test-rule-of-three/main.hpp
new file mode 100644
index 0000000..5cd7ffb
--- /dev/null
+++ b/labb4/test-rule-of-three/main.hpp
@@ -0,0 +1,31 @@
+struct Base {
+ virtual ~Base() {}
+ virtual Base *clone() = 0;
+
+ virtual void hello() = 0;
+};
+
+struct DerivedA : public Base {
+ ~DerivedA() = default;
+ Base *clone() override;
+
+ void hello() override;
+};
+
+struct DerivedB : public Base {
+ ~DerivedB() = default;
+ Base *clone() override;
+
+ void hello() override;
+};
+
+struct GameState {
+ GameState();
+
+ GameState(const GameState &other);
+ GameState &operator=(const GameState &other);
+ ~GameState();
+
+ Base *thing;
+ void switchThing();
+};