【C++】智能指针的模拟实现

本文深入探讨了智能指针的概念,重点介绍了如何模拟实现Auto_ptr和Shared_ptr。Auto_ptr关注拷贝构造和赋值运算符的资源管理,而Shared_ptr则引入了互斥锁和引用计数,确保多线程环境下的安全性。通过实例代码展示了这两个智能指针的使用和关键操作,揭示了它们在内存管理中的重要作用。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<mutex>
using namespace std;

//智能指针的模拟
//内部就是一个需要管理的空间
//构造函数赋值,析构函数清理
//指针要实现*,返回解引用后的空间,->返回指针
//auto_ptr的核心是拷贝构造,赋值运算符的管理权转移(参数一定要引用!!!因为要拿走它的资源)
//赋值运算符因为不是构造,要先判断不是给自己复制,在清理空间再复制,返回*this
template<class T>
class Auto_ptr{
public:
	Auto_ptr(T* ptr=nullptr)
		:_ptr(ptr)
	{}

	~Auto_ptr(){
		if (_ptr != nullptr)
			delete _ptr;
	}

	Auto_ptr(Auto_ptr<T>& a){
		_ptr = a._ptr;
		a._ptr = nullptr;
	}

	Auto_ptr<T>& operator=(Auto_ptr<T>& a){//返回的是智能指针,也就是整个智能指针对象(引用提高效率)
		if (&a != this){						//也就是*this
			if (this->_ptr)
				delete _ptr;//delete
			_ptr = a._ptr;
			a._ptr = nullptr;
		}
		return *this;
	}

	T& operator*(){ return *_ptr; }//解引用当然拿到的是数值内容,是返回引用
	T* operator->(){ return _ptr; }//箭头是指拿到内部的东西,也就是拿到指针

private:
	T* _ptr;
};

//unique_ptr就是禁用了拷贝构造和赋值运算符的unique_ptr;



//shared_ptr需要自己在内部维护互斥锁指针和引用计数指针
//特殊点在于拷贝构造,赋值运算符计数+1,构造不用,析构要看情况析构
//计数加一要加锁,释放需要加锁(注意如果计数为0,解锁后才释放资源)
template <class T>
class Shared_ptr{
public:
	Shared_ptr(T* ptr=nullptr)
		:_ptr(ptr),
		_mutex(new mutex),
		_count(new int(1))
	{}

	~Shared_ptr(){
		Release();
	}
	
	void countadd(){
		_mutex->lock();
		(*_count)++;	//注意要解引用
		_mutex->unlock();
	}
	
	Shared_ptr (const Shared_ptr<T>& p)
		:_ptr(p._ptr),
		_mutex(p._mutex),
		_count(p.count)
	{
			countadd();
	}

	Shared_ptr<T>& operator=(Shared_ptr<T>& p){
		if (this != &p){
			Release();//释放this的智能指针的空间
			_ptr = p.ptr;
			_mutex = p._mutex;
			_count = p._count;
			countadd();
		}
		return *this;
	}
	T& operator*() { return *_ptr; }
	T* operator->() { return _ptr; }
	int UseCount() { return *_pRefCount; }

private:
	void Release(){
		bool m = flase;
		_mutex->lock();
		if ((--(*_count)) == 0){
			delete _count;
			delete _ptr;
			m = true;
		}
		_mutex->unlock();
		if (m){
			delete _mutex;
		}
	}
	T* _ptr;
	mutex* _mutex;
	int* _count;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值