shared_ptr简单实现
来源:互联网 发布:android电视直播软件 编辑:程序博客网 时间:2024/05/16 07:21
实现一个简单的shared_ptr
翻看以前的代码的时候发现一个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)。
源码如下:
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
阅读全文
0 0
- shared_ptr 的简单实现
- shared_ptr简单实现
- 简单实现auto_ptr,shared_ptr,weak_ptr
- 实现一个简单的shared_ptr
- 实现一个简单的 shared_ptr
- 实现一个简单的shared_ptr
- shared_ptr智能指针的简单实现
- 智能指针shared_ptr 的简单实现
- shared_ptr 实现
- shared_ptr 实现
- C++简单版shared_ptr智能指针的实现
- shared_ptr 最简单应用
- boost shared_ptr实现浅析
- 模拟实现shared_ptr
- c++ shared_ptr指针实现
- 模拟实现shared_ptr
- boost::shared_ptr 分析与实现
- boost::shared_ptr 分析与实现
- Linux常用命令手册
- C
- ubuntu下面 将桌面换成 英文
- Java求给定数组的最长递增子序列
- 数据库隔离级别---MySQL的默认隔离级别就是Repeatable,Oracle默认Read committed,最高级别Serializable
- shared_ptr简单实现
- 【c】三子棋
- Count
- vs文件路径问题
- Linux服务器上监控网络带宽的18个常用命令
- JDBC oracle thin 连接方式
- iptables:tproxy做透明代理
- sed正则表达式匹配,各种括号的转义和不转义
- PCB电路板单点与多点接地有什么区别