智能指针(还缺少scoped_ptr的模拟实现)
来源:互联网 发布:微信抓取朋友圈数据库 编辑:程序博客网 时间:2024/05/22 09:04
以下四个智能指针都是boost库中的1.auto_ptr 管理权转移,带有缺陷的设计。尽量不要使用它2.scoped_ptr 防拷贝,高效简洁。不需要拷贝/赋值,尽量使用它3.shared_ptr 共享(引用计数)管理、支持赋值/拷贝。缺陷:循环使用(针对循环使用有weak_ptr).4.weak_ptr辅助shared_ptr解决循环引用,不增加引用计数。
下面是关于auto_ptr的模拟实现
template<class T>class AutoPtr{public: AutoPtr(T* ptr) :_ptr(ptr) {} AutoPtr(AutoPtr<T>& ap) :_ptr(ap._ptr) { ap._ptr = NULL; } ~AutoPtr() { if (_ptr) { cout << _ptr << endl; delete[] _ptr; _ptr = NULL; } } T& operator *() { return *_ptr; } T* operator ->() { return _ptr; }protected: T* _ptr;};struct AA{ int _a1; int _a2;};int main(){ AutoPtr<int> ap1(new int(10)); *ap1 = 20; AutoPtr<AA> ap2(new AA); (*ap2)._a1 = 10; (*ap2)._a2 = 20; ap2->_a1 = 30; ap2->_a2 = 40; system("pause"); return 0;}
下面是关于shared_ptr的模拟实现
emplate<class T>class SharedPtr{public: SharedPtr(T* ptr) :_ptr(ptr) , _countRef(new int(1)) {} SharedPtr(const SharedPtr<T>& sp) :_ptr(sp._ptr) , _countRef(sp._countRef) { ++(*_countRef); } SharedPtr<T>& operator=(const SharedPtr<T>& sp) { if (_ptr != sp._countRef) { Release(); _ptr = sp._ptr; _countRef = sp._countRef; ++(*_countRef); } return *this; } ~SharedPtr() { Release(); } T& operator *() { return *_ptr; } T* operator ->() { return _ptr; } inline void Release() { if (--(*_countRef) == 0) { cout << _ptr << endl; delete _ptr; delete _countRef; } } int UseCount() { return *_countRef; }protected: T* _ptr; int* _countRef;//引用计数};
阅读全文
0 0
- 智能指针(还缺少scoped_ptr的模拟实现)
- 智能指针的模拟实现 auto_ptr scoped_ptr shared_ptr
- 智能指针:模拟实现auto_ptr,scoped_ptr,shared_ptr
- 模拟实现auto_ptr、scoped_ptr、shared_ptr等智能指针
- 【C++】智能指针的作用,模拟实现auto_ptr,scoped_ptr,shared_ptr,scoped_array,shared_array
- 智能指针(auto_ptr scoped_ptr)
- 模拟实现C++/boost库智能指针auto_ptr scoped_ptr和share_ptr
- 智能指针的模拟实现
- 智能指针scoped_ptr组件的使用
- 智能指针(三)之scoped_ptr
- 智能指针 scoped_ptr
- 智能指针scoped_ptr
- 智能指针 scoped_ptr
- 关于scoped_ptr智能指针
- scoped_ptr智能指针(二)
- 智能指针boost::scoped_ptr
- Boost智能指针:scoped_ptr
- 智能指针(二):scoped_ptr
- SVN使用教程之——分支、合并
- Java线程池总结
- resin注意事项
- 洛谷 P1070 Vijos 1815 [NOIP 2009]道路游戏
- HTML超链接
- 智能指针(还缺少scoped_ptr的模拟实现)
- Map集合根据key排序
- thread24
- JAVA的解释执行
- JavaScript面向对象(2)——函数与闭包(函数、对象、闭包)
- PostreSQL崩溃试验全记录
- IIS 之 在IIS7、IIS7.5中应用程序池最优配置方案
- LeetCode ——566. Reshape the Matrix
- thread25