智能指针实现

智能指针实现

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
请按任意键继续. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值