I'm trying to realize a smart pointer by myself. I know that I can use smart pointers instead of this but I'm trying to do this only for understanding smart pointers structure.
Тhe problem is the following when my smart pointer has been starting to call the destructor, this is checking if my pointer is not nullptr then if it is true this will delete ptr.
After this when the destructor has been calling again for CastS I'm getting an exception because the destructor is trying to delete an already deleted element and my if statement for the second time isn't working (as I was expecting) because after the deletion of an element the address is changing and the pointer isn't null anymore.
How Can I improve this code and how can I not delete twice already deleted pointer?
#include <iostream> #include <string> #include <chrono> #include <thread> #include <memory> using std::cout; using std::endl; template<typename T> class Smart_Pointer { private: T* ptr; public: Smart_Pointer(T* ptr); ~Smart_Pointer(); T& operator*(); }; template<typename T> Smart_Pointer<T>::Smart_Pointer(T* ptr) { this->ptr = ptr; } template<typename T> Smart_Pointer<T>::~Smart_Pointer() { if (ptr != nullptr) { delete ptr; ptr = nullptr; } } template<typename T> T& Smart_Pointer<T>::operator*() { return *ptr; } int main() { Smart_Pointer<int> castS(new int(10)); Smart_Pointer<int> castS2 = castS; }
delete ptr;word just fine ifptris a null pointer; there's no need forif (ptr != nullptr). And settingptr = nullptr;after the delete is pointless, because the object is being destroyed, andptrwill no longer exist.Smart_Pointer(Smart_Pointer const&) = delete;because the compiler generated copy constructor won't work. AndSmart_Pointer& operator=(Smart_Pointer const&) = delete;for the assignment operator, for the same reasons.