智能指针 Shared_ptr 简单实现

本文详细介绍了C++11中的智能指针shared_ptr,包括其功能、内部数据结构、核心模块及其实现原理。通过引用计数确保了对象在不再使用时自动释放,有效防止内存泄漏和悬空指针问题。文中还给出了一个简单的shared_ptr实现示例,展示了构造、赋值、解引用和引用计数等功能。
摘要由CSDN通过智能技术生成

shared_ptr概述

shared_ptr是C++11中提供的一个智能指针类,可以在任何位置都不使用时自动删除指针,从而彻底消除内存泄露和悬空指针问题。它在设计过程中遵循共享所有权的概念,即不同的shared_ptr可以引用同一个指针,并在内部使用计数器机制来实现这一点。
每个 shared_ptr 对象在内部指向两个内存位置:

  1. 指向对象的指针。
  2. 用于控制引用计数数据的指针。

共享所有权如何在参考计数的帮助下工作:

  1. 当新的 shared_ptr 对象与指针关联(复制构造,赋值等)时,则在其构造函数中,将与此指针关联的引用计数增加1。
  2. 当任何 shared_ptr 对象超出作用域时,则在其析构函数中,它将关联指针的引用计数减1。
  3. 如果引用计数变为0,则表示没有其他 shared_ptr 对象与此内存关联,在这种情况下,它使用delete函数删除该内存。

shared_ptr数据结构

为了实现共享所有权功能,我们采用如下的数据结构来完成。

class smart{
private:
		T* _ptr;
	int* _count;
...
};

shared_ptr主要模块

smart(T* ptr = nullptr)
smart(const smart& ptr)
smart& operator=(const smart& ptr)
T& operator*()
T& operator->()
~smart()
int use_count()

模块结构图如下:
在这里插入图片描述

代码实现

#include <memory>
#include<iostream>
using namespace std;

template<typename T>
class smart
{
private:
	T* _ptr;
	int* _count;
public:
	smart(T* ptr = nullptr) :_ptr(ptr)
	{
		if (_ptr)
		{
			_count = new int(1);
		}
		else
		{
			_count = new int(0);
		}
	}
	smart(const smart& ptr)
	{
		if (this != &ptr)
		{
			this->_ptr = ptr._ptr;
			this->_count = ptr._count;
			(*this->_count)++;
		}
	}
	smart& operator=(const smart& ptr)
	{
		if (this->_ptr == ptr._ptr)
		{
			return *this;
		}
		if (this->_ptr)
		{
			(*this->_count)--;
			if (this->_count == 0)
			{
				delete this->_ptr;
				delete this->_count;
			}
		}
		this->_ptr = ptr._ptr;
		this->_count = ptr._count;
		(*this->_count)++;
		return *this;
	}

	//operator*重载
	T& operator*()
	{
		if (this->_ptr)
		{
			return *(this->_ptr);
		}
	}

	//operator->重载
	T& operator->()
	{
		if (this->_ptr)
		{
			return this->_ptr;
		}
		else
		{
			return nullptr;
		}
	}

	//析构函数
	~smart()
	{
		(*this->_count)--;
		if (*this->_count == 0)
		{
			delete this->_ptr;
			delete this->_count;
		}
	}
	//return reference couting
	int use_count()
	{
		return *this->_count;
	}
};
int main()
{
	smart<int> sm(new int(10));
	cout << "operator*():" << *sm << endl;
	cout << "reference couting:(sm)" << sm.use_count() << endl;
	smart<int> sm2(sm);
	cout << "copy ctor reference couting:(sm)" << sm.use_count() << endl;
	smart<int> sm3;
	sm3 = sm;
	cout << "copy operator= reference couting:(sm)" << sm.use_count() << endl;
	cout << &sm << endl;
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值