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

 

参考博客:http://www.cnblogs.com/xiehongfeng100/p/4645555.html

转载于:https://www.cnblogs.com/zpcoding/p/10739044.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值