C/C++自能指针 测试和手动实现

 1 #include <iostream>
 2 #include <memory>
 3 
 4 using namespace std;
 5 class  A
 6 {
 7 public:
 8     A(int a)
 9     {
10         cout << "A()...." << endl;
11         this->a = a;
12     }
13     void func()
14     {
15         cout << "a=" << this->a << endl;
16     }
17     ~A()
18     {
19         cout << "~A()...." << endl;
20     }
21 private:
22     int a;
23 };
24 //auto_ptr<A> ptr(new A(10));
25 
26 class MyAutoPtr
27 {
28 public:
29     MyAutoPtr(A* ptr)
30     {
31         this->ptr = ptr; //new A(10)
32     }
33     ~MyAutoPtr()
34     {
35         if (this->ptr != NULL)
36         {
37             delete ptr;
38             this->ptr = NULL;
39         }
40     }
41     A* operator->()
42     {
43         return this->ptr;
44     }
45     A& operator*()
46     {
47         return *(this->ptr);
48     }
49 private:
50     A* ptr;
51 };
52 
53 void test01()
54 {
55 #if 0
56     A * ap = new A(10);
57     ap->func();
58     (*ap).func();
59     delete ap;
60 #endif
61     auto_ptr<A> ptr(new A(10));
62     ptr->func();
63     (*ptr).func();
64 }
65 void test02()
66 {
67     MyAutoPtr my_p(new A(10));
68 
69     my_p->func();     //my_p.ptr -> func()
70     (*my_p).func();   //  *ptr.func()
71 }
72 
73 int main()
74 {
75     //test01();
76     test02();
77     cout << endl;
78     cout << "结束" << endl;
79     system("pause");
80     return 0;
81 }

 

posted @ 2018-08-03 15:15  LifeOverflow  阅读(190)  评论(0编辑  收藏  举报