Website Summary Files Commits Branches @commit @diff @stats
path: root / Week11 / Exercise06
diff options
context:
space:
mode:
2 files changed, 84 insertions, 0 deletions
-rw-r--r--Week11/Exercise06/UniquePointer.hpp75
-rw-r--r--Week11/Exercise06/main.cpp9
diff --git a/Week11/Exercise06/UniquePointer.hpp b/Week11/Exercise06/UniquePointer.hpp
new file mode 100644
index 0000000..fe95234
--- /dev/null
+++ b/Week11/Exercise06/UniquePointer.hpp
@@ -0,0 +1,75 @@
+#ifndef _UNIQUEPOINTER
+#define _UNIQUEPOINTER
+
+template<class T>
+class UniquePointer {
+ T* value;
+
+public:
+ UniquePointer(T* value);
+
+ UniquePointer();
+ ~UniquePointer();
+
+ UniquePointer(UniquePointer&& other);
+ UniquePointer& operator=(UniquePointer&& other);
+
+ T& operator*();
+ const T& operator*() const;
+ T* operator->();
+ const T* operator->() const;
+};
+
+template<class T>
+UniquePointer<T>::UniquePointer(T* value) : value(value)
+{ }
+
+template<class T>
+UniquePointer<T>::UniquePointer() : value()
+{ }
+
+template<class T>
+UniquePointer<T>::~UniquePointer() {
+ delete value;
+}
+
+template<class T>
+UniquePointer<T>::UniquePointer(UniquePointer&& other) {
+ value = other.value;
+
+ other.value = nullptr;
+}
+
+template<class T>
+UniquePointer<T>& UniquePointer<T>::operator=(UniquePointer&& other) {
+ if (this != &other) {
+ delete value;
+
+ value = other.value;
+
+ other.value = nullptr;
+ }
+ return *this;
+}
+
+template<class T>
+T& UniquePointer<T>::operator*() {
+ return *value;
+}
+
+template<class T>
+const T& UniquePointer<T>::operator*() const {
+ return *value;
+}
+
+template<class T>
+T* UniquePointer<T>::operator->() {
+ return value;
+}
+
+template<class T>
+const T* UniquePointer<T>::operator->() const {
+ return value;
+}
+
+#endif /* _UNIQUEPOINTER */
diff --git a/Week11/Exercise06/main.cpp b/Week11/Exercise06/main.cpp
new file mode 100644
index 0000000..8853a90
--- /dev/null
+++ b/Week11/Exercise06/main.cpp
@@ -0,0 +1,9 @@
+#include "UniquePointer.hpp"
+#include <utility>
+
+int main() {
+ UniquePointer<int> ptr(new int);
+ // Този ред, без "std::move", ще хвърли грешка,
+ // понеже нямаме копиращи семантики
+ UniquePointer<int> ptr1 = std::move(ptr);
+}