智能指针(Smart Pointer)
2013-10-24 14:21
281 查看
一个智能指针类
比起一般指针,智能指针会自动地管理内存(释放不需要的内存),而不需要程序员去操心。 它能避免野指针(dangling pointers),内存泄漏(memory leaks), 分配失败等情况的发生。智能指针需要为所有实例维护一个引用计数, 这样才能在恰当的时刻(引用计数为0时)将内存释放。
版本一:
比起一般指针,智能指针会自动地管理内存(释放不需要的内存),而不需要程序员去操心。 它能避免野指针(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; }
相关文章推荐
- 智能指针与弱引用详解
- C++ 智能指针深入解析
- boost 智能指针
- 智能指针
- C++ 智能指针详解
- C++中的智能指针(smart pointer)
- [boost]智能指针简介
- c++智能指针与内存管理
- c++智能指针与内存管理
- C++智能指针auto_ptr
- C++一些注意点之指针成员管理
- WebKit中的智能指针
- shared_ptr
- 如何:创建和使用shared_ptr实例
- Boost.shared_ptr必须注意的一些地方
- 智能指针shared_ptr
- C++ Boost
- 仿照shared_ptr写的一种智能指针(共享型的智能指针)
- 关于Cross-Dll问题(在不同的模块之间申请和释放内存)
- C++ 智能指针详解