shared_ptr的简单实现

shared_ptr:使用引用计数

  1. 传入指针的构造函数
  2. 拷贝构造函数
  3. 赋值函数
  4. 析构函数
  5. 获取引用计数
  6. ->和*的重载

注意事项

  1. 构造函数是explicit的,防止smart_ptr< int > sp = p 的使用
  2. 计数需要用int*
  3. *ptr++是先++的,所以需要括号或者++*ptr

smart_ptr.h

template<typename T>
class smart_ptr
{
	T* ptr;
	int* count;
public:
	explicit smart_ptr(T* p);
	smart_ptr(smart_ptr<T>& other);
	smart_ptr<T>& operator=(smart_ptr<T>& other);
	~smart_ptr();
	int use_count();
	T* operator->();
	T& operator*();
};

smart_ptr.cpp

template<typename T>
smart_ptr<T>::smart_ptr(T* p):
	ptr(p), count(new int(1)) {}

template<typename T>
smart_ptr<T>::smart_ptr(smart_ptr<T>& other)
{
	if (ptr && --*count == 0)
	{
		delete ptr;
		delete count;
	}
	++*other.count;
	ptr = other.ptr;
	count = other.count;
}

template<typename T>
smart_ptr<T>& smart_ptr<T>::operator=(smart_ptr<T>& other)
{
	// TODO: insert return statement here
	if (other.ptr != this->ptr)
	{
		if (ptr && --(*count) == 0)
		{
			delete ptr;
			delete count;
		}
		ptr = other.ptr;
		count = other.count;
		++*count;
	}
	return *this;
}


template<typename T>
smart_ptr<T>::~smart_ptr()
{
	if (ptr && --*count == 0)
	{
		delete ptr;
		delete count;
	}
	ptr = nullptr;
	count = nullptr;
}

template<typename T>
int smart_ptr<T>::use_count()
{
	if (count)
		return *count;
	else
		return 0;
}

template<typename T>
T* smart_ptr<T>::operator->()
{
	return ptr;
}

template<typename T>
T& smart_ptr<T>::operator*()
{
	return *ptr;
}
下面是一个简单shared_ptr 的代码实现: ```cpp template<typename T> class shared_ptr { public: shared_ptr() : ptr(nullptr), ref_count(nullptr) {} shared_ptr(T* p) : ptr(p), ref_count(new int(1)) {} shared_ptr(const shared_ptr& other) : ptr(other.ptr), ref_count(other.ref_count) { if (ref_count) { ++(*ref_count); } } shared_ptr& operator=(const shared_ptr& other) { if (this != &other) { release(); ptr = other.ptr; ref_count = other.ref_count; if (ref_count) { ++(*ref_count); } } return *this; } ~shared_ptr() { release(); } T& operator*() const { return *ptr; } T* operator->() const { return ptr; } operator bool() const { return ptr != nullptr; } T* get() const { return ptr; } private: void release() { if (ref_count) { --(*ref_count); if (*ref_count == 0) { delete ptr; delete ref_count; } ptr = nullptr; ref_count = nullptr; } } T* ptr; int* ref_count; }; ``` 在这个实现中,我们使用一个指针 `ptr` 来保存所指向的对象,使用一个指针 `ref_count` 来保存指向该对象的共享指针数量。当一个新的 shared_ptr 对象创建时,我们将 `ref_count` 初始化为 1,表示当前只有一个 shared_ptr 对象指向该对象。当我们拷贝一个 shared_ptr 对象时,我们将 `ref_count` 增加 1,并与原对象共享同一个指针。当一个 shared_ptr 对象被销毁时,我们将 `ref_count` 减 1,如果此时 `ref_count` 的值为 0,表示没有任何 shared_ptr 对象指向该对象了,我们就可以释放该对象的内存和 `ref_count` 的内存了。 此外,我们还实现了 `operator*` 和 `operator->` 来方便访问所指向的对象,实现了 `operator bool` 来判断 shared_ptr 是否为空,实现了 `get` 函数来获取指向的对象的指针。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值