实现一个简单的shared_ptr
2017-10-29 15:31
441 查看
翻看以前的代码的时候发现一个shared_ptr的简单实现。
我记得是网上的一篇例子(好像改了一点),但是又懒得找出处了 ╮(╯▽╰)╭。
觉得这份代码足以用来初步了解shared_ptr的实现了。
一般来说,智能指针的实现需要以下步骤:
1.一个模板指针T* ptr,指向实际的对象。
2.一个引用次数(必须new出来的,不然会多个shared_ptr里面会有不同的引用次数而导致多次delete)。
3.重载operator*和operator->,使得能像指针一样使用shared_ptr。
4.重载copy constructor,使其引用次数加一。
5.重载operator=,如果原来的shared_ptr已经有对象,则让其引用次数减一并判断引用是否为零(是否调用delete)。
然后将新的对象引用次数加一。
6.重载析构函数,使引用次数减一并判断引用是否为零(是否调用delete)。
源码如下:
我记得是网上的一篇例子(好像改了一点),但是又懒得找出处了 ╮(╯▽╰)╭。
觉得这份代码足以用来初步了解shared_ptr的实现了。
一般来说,智能指针的实现需要以下步骤:
1.一个模板指针T* ptr,指向实际的对象。
2.一个引用次数(必须new出来的,不然会多个shared_ptr里面会有不同的引用次数而导致多次delete)。
3.重载operator*和operator->,使得能像指针一样使用shared_ptr。
4.重载copy constructor,使其引用次数加一。
5.重载operator=,如果原来的shared_ptr已经有对象,则让其引用次数减一并判断引用是否为零(是否调用delete)。
然后将新的对象引用次数加一。
6.重载析构函数,使引用次数减一并判断引用是否为零(是否调用delete)。
源码如下:
1 #ifndef __SHARED_PTR_ 2 #define __SHARED_PTR_ 3 4 template <typename T> 5 class shared_ptr { 6 public: 7 shared_ptr(T* p) : count(new int(1)), _ptr(p) {} 8 shared_ptr(shared_ptr<T>& other) : count(&(++*other.count)), _ptr(other._ptr) {} 9 T* operator->() { return _ptr; } 10 T& operator*() { return *_ptr; } 11 shared_ptr<T>& operator=(shared_ptr<T>& other) 12 { 13 ++*other.count; 14 if (this->_ptr && 0 == --*this->count) 15 { 16 delete count; 17 delete _ptr; 18 } 19 this->_ptr = other._ptr; 20 this->count = other.count; 21 return *this; 22 } 23 ~shared_ptr() 24 { 25 if (--*count == 0) 26 { 27 delete count; 28 delete _ptr; 29 } 30 } 31 int getRef() { return *count; } 32 private: 33 int* count; 34 T* _ptr; 35 }; 36 37 38 #endif
相关文章推荐
- 实现一个简单的shared_ptr
- 实现一个简单的shared_ptr
- C++ 智能指针的一个实现(基于模板和Shared_ptr)
- shared_ptr智能指针的简单实现
- 智能指针shared_ptr 的简单实现
- 自己实现 SharedPtr(4)—— 一个代码洁癖的救赎
- 简单实现auto_ptr,shared_ptr,weak_ptr
- shared_ptr 的简单实现
- 自已实现一个微小的shared_ptr
- shared_ptr的简单实现
- shared_ptr简单实现
- 一个简单的java回调函数的实现
- 一个简单的线程池实现
- 使用python实现一个简单的学生信息管理系统
- IOCP 实现一个简单高并发服务器程序
- [shiro学习笔记]第二节 shiro与web融合实现一个简单的授权认证
- 一个java实现的简单文件下载程序
- auto_ptr的简单实现
- C语言实现的一个简单的万年历