Unique_Ptr Implementation c++ (Smart Pointer)

Amit.Kumar
2 min readFeb 22, 2022

--

//Unique pointer implementation#include <iostream>using namespace std;class A {public :void func1(){cout << “class A : func1()” << endl;}};template<typename T>class uniqueptr {private:T* res;public :uniqueptr(T* param = nullptr) : res(param) { cout << “default ctor” << endl; }uniqueptr(const uniqueptr<T>& obj) = delete;uniqueptr& operator=(const uniqueptr<T>& obj) = delete;uniqueptr(uniqueptr<T>&& obj){cout << “move copy ctor” << endl;res = obj.res;obj.res = nullptr;}uniqueptr& operator=(uniqueptr<T>&& obj){cout << “move assignment operator” << endl;if (this != &obj){if(res) delete res;res = obj.res;obj.res = nullptr;}return *this;}void reset(T* newres = nullptr){cout << “reset function” << endl;if (res)delete res;res = newres;}T* operator->() const{cout << “-> operator called “ << endl;return res;}T& operator*() const{cout << “* operator called” << endl;return (*res);}T* get() const{cout << “get function called” << endl;return res;}~uniqueptr<T>() {cout << “dtor called” << endl;if (res){delete res;res = nullptr;}}operator bool(){cout << “operator bool called” << endl;return res != nullptr;}};int main(){uniqueptr<A> ptr1; //default ctoruniqueptr<A> ptr2(new A); //param ctor//uniqueptr<A> ptr3(ptr1); //copy ctor -> should not be possible//ptr3 = ptr2; //copy assignment operator -> should not be possibleuniqueptr<A> ptr4 = std::move(ptr2); // move copy ctorptr4 = std::move(ptr2); // move copy assignment operatorptr1.reset(new A); // reset member functionptr1->func1(); // overload -> operator(*ptr1).func1(); // overload * operatorA* obj = ptr1.get(); // get() member functionif (ptr1){ptr1->func1();}//need to have destructorreturn 0;}

--

--

Amit.Kumar
Amit.Kumar

Written by Amit.Kumar

I have been a coder all my life . And yes a dreamer too. But i am also interested in understanding different aspects of life .

No responses yet