智能指针实现
Shared_ptr实现
1. 原理
shared_ptr指针中存放 对象的指针,并且存放一个 refCount的指针 来对当前对象被引用的数量进行记录。
即:
private:
T* data;
int* refCount;
需要实现的为:
- 模板类即模板函数声明
- 默认构造函数
- 构造函数
- 复制构造函数
- 赋值操作符重载 operator=
- 析构函数
- 解引用操作符 * 重载
- 指针操作符 -> 重载
2. 代码实现
#include <iostream>
#include <string>
using namespace std;
template <class T>
class mshared_ptr{
private:
T* data;
int * cnt;
public:
mshared_ptr(T* d);
mshared_ptr():data(nullptr),cnt(0) {}
mshared_ptr(mshared_ptr<T>& obj);
mshared_ptr& operator=(mshared_ptr<T>& obj);
T& operator*() { return *data; }; //解引用重载,当前类作为指针
T* operator->() { return cnt>0 ? (data):0; } //箭头重载,当前类作为指针
~mshared_ptr();
};
template<class T>
mshared_ptr<T>::mshared_ptr(T* d){
data = d;
cnt = new int(1);
cout<<"[Construct] Create obj:"<<*data<<". "<<" cnt"<<*cnt<<endl;
}
template <class T>
mshared_ptr<T>::mshared_ptr(mshared_ptr<T>& obj){
data = obj.data;
cnt = obj.cnt;
++(*cnt);
cout<<"[Copy construct] from obj:"<<*data<<". "<<"update cnt"<<*cnt<<endl;
}
template<class T>
mshared_ptr<T>::~mshared_ptr(){
--(*cnt);
cout<<"[Destruct] update cnt:"<<*cnt;
if(data && (*cnt)==0){ //已经减1了
cout<<" Delete obj: "<<*data;
delete data;
delete cnt;
}
cout<<endl;
}
template<class T>
mshared_ptr<T>& mshared_ptr<T>::operator=(mshared_ptr<T>& obj){
cout<<"[Operator = ]";
if(data && --(*cnt)==0){ //已经减1了
cout<<" delete former obj: "<<*data;
delete data;
delete cnt;
}
data = obj.data;
cnt = obj.cnt;
++(*cnt);
cout<<" update obj:"<<*data<<". "<<"update cnt"<<*cnt<<endl;
return *this;
}
3. 测试
int main(){
{
mshared_ptr<string> pstr(new string("abc"));
cout<<pstr->size()<<endl;
cout<<*pstr<<endl;
mshared_ptr<string> pstr2(pstr);
mshared_ptr<string> pstr3(new string("hao"));
pstr3 = pstr2;
}
system("pause");
return 0;
}
结果显示:
[Construct] Create obj:abc. cnt1
3
abc
[Copy construct] from obj:abc. update cnt2
[Construct] Create obj:hao. cnt1
[Operator = ] delete former obj: hao update obj:abc. update cnt3
[Destruct] update cnt:2
[Destruct] update cnt:1
[Destruct] update cnt:0 Delete obj: abc
pdate obj:abc. update cnt3
[Destruct] update cnt:2
[Destruct] update cnt:1
[Destruct] update cnt:0 Delete obj: abc
请按任意键继续. . .