智能指针(Smart Pointer)
来源:互联网 发布:淘宝店与客人聊天 编辑:程序博客网 时间:2024/05/17 22:39
一个智能指针类
比起一般指针,智能指针会自动地管理内存(释放不需要的内存),而不需要程序员去操心。 它能避免野指针(dangling pointers),内存泄漏(memory leaks), 分配失败等情况的发生。智能指针需要为所有实例维护一个引用计数, 这样才能在恰当的时刻(引用计数为0时)将内存释放。
版本一:
#include <iostream>#include <cstdlib>using namespace std;template <typename T>class SmartPointer{protected: T *ref;unsigned *ref_count;private:void clear(){delete ref;free(ref_count);ref = NULL; // 避免它成为野指针ref_count = NULL;}public:SmartPointer(T* ptr)//构造函数{cout<<"constructor"<<endl;ref = ptr;ref_count = (unsigned*)malloc(sizeof(unsigned));*ref_count = 1;}SmartPointer(SmartPointer<T>& sptr)//复制构造函数{cout<<"copy constructor"<<endl;ref = sptr.ref;ref_count = sptr.ref_count;++*ref_count;}SmartPointer<T>& operator=(SmartPointer<T> &sptr)//赋值构造函数{if (this != &sptr) {if (--*ref_count == 0)//左操作数ref_count减1,右操作数ref_count加1,因为左操作数将被右操作数覆盖{clear();cout<<"operator= clear"<<endl;}ref = sptr.ref;ref_count = sptr.ref_count;++*ref_count;//右操作数+1}return *this;}~SmartPointer(){if (--*ref_count == 0){clear();cout<<"destructor clear"<<endl;}}T getValue() { return *ref; }};int main(){int *ip1 = new int();*ip1 = 1;int *ip2 = new int();*ip2 = 2;SmartPointer<int> sp1(ip1), sp2(ip2); //显式调用构造函数SmartPointer(T* ptr)//隐式调用复制构造函数SmartPointer(SmartPointer<T>& sptr),等价于SmartPointer<int> spa = SmartPointer<int>(sp1);SmartPointer<int> spa = sp1;sp2 = spa; // 调用赋值构造函数return 0;}
- Smart Pointer--智能指针
- 智能指针(smart pointer)
- 智能指针(smart pointer)
- 智能指针(Smart Pointer)
- 智能指针 smart pointer
- C++ 智能指针(Smart Pointer)
- C++ 智能指针(Smart Pointer)
- 理解智能指针(Smart Pointer)
- 智能指针(Smart Pointer) [一]
- C++:智能指针(Smart Pointer)
- 智能指针(smart pointer)
- 【C++】智能指针(Smart Pointer)
- COM智能指针(Smart Pointer)的陷阱
- 深度探索智能指针(Smart Pointer)
- 什么是智能指针 what is smart pointer
- 智能指针(Smart Pointer)的实现
- C++中的智能指针(Smart Pointer)
- C++中的智能指针(smart pointer)
- Kinect for Windows SDK开发入门(一):开发环境配置
- Beanstalk
- 3分钟写出来的Jquery版checkbox全选反选功能
- NSInvocation的使用
- C语言的那些事——scanf()和gets()在字符串中出现空格时的区别比较
- 智能指针(Smart Pointer)
- JPA的主键产生策略
- android clip
- Centos6.3中安装GlassFish3.1.2.2
- 深入理解硬盘的Linux分区
- C# Label显示多行文本及换行(WinForm/WebForm)
- YARN概述
- 适配iOS7之—UITableView和UISearchBar
- java String类