Introduction: Key points for writing smart pointers:
A) The constructor receives heap memory
b) destructor frees memory
c) Prohibit value semantics if necessary.
d) overloaded * with two operator characters
1 #ifndef Start_ptr_h2 #defineStart_ptr_h3 4#include <iostream>5 using namespacestd;6 7 classAnimal8 {9 Public:TenAnimal () {cout <<"Animal"<<Endl;} One~animal () {cout <<"~animal"<<Endl;} A - voidRun () {cout <<"Animal is running ....."<<Endl;} - the }; - - - + - classSmartptr + { A Public: atSmartptr (Animal * ptr = NULL)//using the default function - :p tr_ (PTR) - { - - } - in~smartptr () - { to Delete ptr_; + } - theAnimal &operator*()//a const version needs to be overloaded, otherwise const SMARTPTR cannot be dereferenced * { $ return*ptr_;Panax Notoginseng } - ConstAnimal &operator*()Const the { + return*ptr_; A } the +Animal *operator-() - { $ returnptr_; $ } - ConstAnimal *operator()Const - { the returnptr_; - }Wuyi Private: theSmartptr (ConstSmartptr &Other ) - :p tr_ (other.ptr_) Wu { - About } $Smartptr &operator=(ConstSmartptr &Other ) - { - if( This! = &Other ) - { APtr_ =other.ptr_; + } the return* This ; - } $ theAnimal *ptr_; the } ; the the #endif/*start_ptr_h*/
Test code:
1#include"SmartPtr.h"2#include <iostream>3 using namespacestd;4 5 intMainintargcConst Char*argv[])6 {7 {8Smartptr PTR (NewAnimal);//The life cycle of this smart pointer is limited to the inside of this curly brace, so the life of the object it holds is only in this pair of parentheses9Ptr->run ();//because the holding object is defined in the constructor of the smart pointer, the holding object is freed in the smart pointer destructor, and the resources obtained by Automation management are realized .Ten } One return 0; A}
is running ..... ~animal
Print results, smart pointers for automatic memory management
Summarize:
In fact
A smart pointer is a class object, but behaves like a pointer. It has three types of operators
a). The method that invokes the object itself is the smart pointer.
b) * Call is to dereference the object held
c) Call is the member inside the calling hold object
C + + Learning Path: Getting Started with smart pointers