c++ 中的智能指针实现

摘要:C++11 中新增加了智能指针来预防内存泄漏的问题,在 share_ptr 中主要是通过“引用计数机制”来实现的。我们今天也来自己实现一个简单的智能指针:

 1 // smartPointer.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include<windows.h>
 7 
 8 using namespace std;
 9 
10 
11 class Person
12 {
13 public:
14     Person(){ count = 0; };
15     ~Person() { };
16     void inc(){ count++; }
17     void dec(){ count--; }
18     int getCount(){ return count; }
19     void printInfo() {
20         cout << "just a test function" << endl;
21     }
22 
23 private:
24     int count;  // 增加类的计数成员,在执行智能指针对象的析构函数时,进行判断是否要 delete 这个对象
25 };
26 
27 
28 class smartPointer
29 {
30 public:
31     smartPointer(){ p = nullptr; };
32     smartPointer(Person *other);         // 带参构造函数
33     smartPointer(smartPointer &other) {  // 拷贝构造函数
34         p = other.p;
35         p->inc();
36     }
37     Person *operator->() {  // 重载 ->
38         return p;
39     }
40     Person& operator*() {   // 重载 *
41         return *p;
42     }
43 
44     ~smartPointer();
45 private:
46     Person *p;
47 };
48 
49 smartPointer::smartPointer(Person *other) {
50     cout << "Person()" << endl;
51     p = other;
52     p->inc();
53 }
54 
55 smartPointer::~smartPointer()
56 {
57     cout << "~Person()" << endl;
58     if (p) {
59         p->dec();
60         if (p->getCount() == 0) {
61             delete p;
62             p = nullptr;
63         }// if            
64     }//if
65 }
66 
67 void test_func(smartPointer& other) {
68     smartPointer s = other;
69     s->printInfo();
70 }
71 
72 
73 int _tmain(int argc, _TCHAR* argv[])
74 {
75     smartPointer sp = new Person();  // 调用带参构造函数( sp 对象中的指针 p 指向构造的 Person 对象)
76     (*sp).printInfo();
77 
78     system("pause");
79     return 0;
80 }
smartPointer

猜你喜欢

转载自www.cnblogs.com/zpcoding/p/10739044.html