I remember the interview was asked the smart pointer implementation, when the smart pointer just heard but did not know, and then said in a muddle. Today I wrote the smart pointer, using the concept of reference counting.
The main idea is to use a new class to encapsulate the originally needed type, the new class holds the original object pointer and a reference count pointer, the reason is all with pointers to save, because there will be more than one new class of object reference to the same pointer, In this case, when we modify the contents of the original object and the reference count, it is natural to ensure that other new class objects are referenced to the latest, and in order to let us think that the object of the new class is also a "pointer", reload the new class "," and "*" operator. The code is directly below, but there are a few caveats to the usage.
#include <stdlib.h> #include <stdio.h> #include <iostream> #include <stdexcept>class ctest{ Public:ctest () {printf ("ctest::construct function\n");} ~ctest () {printf ("CTest::D econstruct function\n");} void Print () {printf ("ctest:print\n");}}; Template<class t>class smartpointer{public:smartpointer (t* p = NULL):p TR (P), Puse (New size_t (1)) {}smartpointer ( Const smartpointer& SP):p tr (sp.ptr), Puse (sp.puse) {++*puse;} smartpointer& operator= (const smartpointer& SP) {++*sp.puse;decuse ();p use = Sp.puse;ptr = Sp.ptr;} Const t* operator-> () const{if (PTR) return Ptr;throw std::runtime_error ("Access null pointer");} t* operator-> () {if (PTR) return Ptr;throw std::runtime_error ("Access null pointer");} Const t& operator* () const{if (PTR) return *ptr;throw std::runtime_error ("Access null pointer");} t& operator* () {if (PTR) return *ptr;throw std::runtime_error ("Access null pointer");//printf ("Access null pointer\n ");} ~smartpointer () {decuse ();p rintf ("Smartpointer deconsTruct\n ");} private:t* ptr;size_t* puse;void Decuse () {if (--*puse = = 0) {if (PTR) Delete Ptr;delete puse;ptr = Null;puse = NULL;}}; int main () {//correctsmartpointer<ctest> T (new CTest); T->print (); smartpointer<ctest> tt (t); Tt->print (); Smartpointer<ctest> TTT;TTT = tt;//wrongctest* nt = new CTest; Smartpointer<ctest> Errott (NT); Smartpointer<ctest> errotT1 (NT);}
The original type in the code above is CTest, and this smart pointer method has a limitation that the same pointer cannot be multiple times as an argument to the Smartpointer constructor, as the last three innings in the main function is the wrong use.
C + + Smart pointers