diff --git a/main.cpp b/main.cpp index 4d9e598..f80c950 100644 --- a/main.cpp +++ b/main.cpp @@ -5,7 +5,7 @@ template class UniquePtr { public: - /// Constructor without deleter + /// Constructor without custom deleter - use default deleter which just calls 'delete' explicit UniquePtr(T *object) : object(object), deleter([](T *object) -> void { delete object; }) { assert(object != nullptr); } @@ -32,14 +32,20 @@ public: /// Move assignment operator UniquePtr &operator=(UniquePtr &&other) { - object = other.object; + Swap(other.object); deleter = other.deleter; + // TODO: If Swap is implemented with std::swap instead of deleting the current object, this should not be done! + // However, that would mean that the old object can stay in memory unnecessarily long (until 'other' goes out of scope) other.object = nullptr; } /// Destructor virtual ~UniquePtr() { + // TODO: deleter(object) is called twice if 'Reset()' was previously called and the UniquePtr goes out of scope. + // With the default deleter, this is fine since 'delete object' handles the case of the object being null. + // However, with a custom deleter this may not be intended? + // We'd have to introduce a new flag and an if statement here deleter(object); } @@ -67,7 +73,7 @@ public: return returnObject; } - /// Reset the internal pointer to null + /// Reset the internal pointer to null, deleting the owned object void Reset() { deleter(object); @@ -120,6 +126,7 @@ private: int TestObject::instanceCount = 0; + void customTestObjectDeleter(TestObject *object) { std::cout << "Custom deleter" << std::endl; @@ -151,9 +158,14 @@ int main() { if (pointer3) { std::cout << "This shouldn't happen!" << std::endl; } + + std::cout << "Moving into a pointer which already has an object" << std::endl; + UniquePtr pointer4 = UniquePtr(new TestObject()); + UniquePtr pointer5 = UniquePtr(new TestObject()); + pointer4 = std::move(pointer5); } - std::cout << std::endl << "All pointers should now be out of scope!" << std::endl; + std::cout << std::endl << "All pointers are now out of scope, all objects should be deleted!" << std::endl; std::cout << TestObject::getInstanceCount() << " instances left" << std::endl; return 0;