C ++ syntax small note --- smart pointers

Smart Pointers
  • To alleviate the problem of memory leaks

  • Pointer used to replace the native

  • Army Regulation: can only point to the heap object or variable space

  • method

    • Call delete destructor smart pointers in

    • Overload "->" operator, can function as a member of overloading, and not have parameters

    • Prohibit smart pointer arithmetic

    • One pair of space can only be directed to a smart pointer

 

example

 1 #include<iostream>
 2 #include<string>
 3 
 4 using namespace std;
 5 
 6 class Persion
 7 {
 8     string name;
 9     int age;
10 public:
11     Persion(string name, int age)
12     {
13         this->name = name;
14         this->age = age;
15         cout<<"Persion()"<<endl;
16     }
17     
18     void show()
19     {
20         cout<<"name = "<<name<<endl;
21         cout<<"age = "<<age<<endl;
22     }
23     
24     ~Persion()
25     {
26         cout<<"~Persion()"<<endl;
27     }
28 };
29 
30 template<typename T>
31 class Pointer
32 {
33     T* m_ptr;
34 public:
35     Pointer(T* ptr)
36     {
37         m_ptr = ptr;
38     }
39     
40     Pointer(const Pointer& other)
41     {
42         m_ptr = other.m_ptr;
43         const_cast<Pointer&>(other).m_ptr = NULL;
44     }
45     
46     Pointer& operator = (const Pointer& other)
47     {
48         if(this != &other)
49         {
50             if(m_ptr)
51             {
52                 delete m_ptr;
53             }
54             
55             m_ptr = other.m_ptr;
56             const_cast<Pointer&>(other).m_ptr = NULL;
57         }
58         return *this;
59     }
60     
61     T* operator -> ()
62     {
63         return m_ptr;
64     }
65     
66     ~Pointer()
67     {
68         if(m_ptr)
69         {
70             delete m_ptr;
71         }
72         m_ptr = NULL;
73     }
74 };
75 
76 int main()
77 {
78     Pointer<Persion> p = new Persion("zhangsan", 20);
79     Pointer<Persion> p1 = NULL;
80     p1 = p;
81     p1->show();
82     return 0;
83 }

 

Guess you like

Origin www.cnblogs.com/chusiyong/p/11295230.html