shared_ptr 实现

shared_ptr是C++11 引入的新特性,用来管理内存,防止内存泄漏

1. shared_ptr 的大小相当于裸指针的两倍,因为shared_ptr内部一般包含了一个指向该资源的裸指针,也包含一个指向该资源的引用计数的裸指针;

void test() {
    int *pInt = new int(0);
    auto sizePInt = sizeof(pInt);  // sizePInt = 8, 指针长度为8

    std::shared_ptr<int> sharedInt(new int (1));
    auto sizeSharedInt = sizeof(sharedInt); // sizeSharedInt = 16,因为包含了两个指针
}

2. 引用计数器的内存必须是动态分配的;

3. 引用计数器的递增和递减必须是原子操作。

shared_ptr 的内存结构(参考 Effective Modern C++)

shared_ptr 的简单实现

#ifndef __SHARED_PTR_H__
#define __SHARED_PTR_H__


template<typename T>
class Shared_ptr {
public:
	Shared_ptr(T* ptr) : m_ptr(ptr) {
		if (ptr != nullptr) {
			m_pCount = new int(1);
		}
		else {
			m_pCount = new int(0); //当指针为空时,*m_pCount = 0
		}
	}

	~Shared_ptr() {
		if (*m_pCount > 0) {
			(*m_pCount)--;
		}
		
		
		if (*m_pCount == 0) { //当*m_pCount为0时,释放相关资源
			delete m_pCount;
			m_pCount = nullptr;

			delete m_ptr;
			m_ptr = nullptr;
		}
	}

	Shared_ptr(const Shared_ptr& other) {
		if (&other != this) {
			m_pCount = other.m_pCount;
			if (*m_pCount > 0) {  // 排除 other.m_ptr= nullptr的时,other.m_pCount = 0的情况
				(*m_pCount)++;
			}

			m_ptr = other.m_ptr;
		}
	}

	Shared_ptr& operator= (const Shared_ptr &other) {
		if (&other == this) {
			return *this;
		}
		
		if (*m_pCount > 0) {
			m_pCount--;
		}
		
		if (*m_pCount == 0) { //释放之前申请的内存
			if (m_ptr == nullptr) {
				delete m_ptr;
			}
			if (m_pCount == nullptr) {
				delete m_pCount;
			}
		}

		m_pCount = other.m_pCount;
		if (*m_pCount > 0) {
			(*m_pCount)++;
		}
		
		m_ptr = other.m_ptr;

		return *this;
	}

	T& operator*() const {
		return *m_ptr;
	}

	T* operator->() const {
		return m_ptr;
	}

	T* get() {
		return m_ptr;
	}

	long int use_count() {
		return *m_pCount;
	}

private:
	int* m_pCount = nullptr;
	T* m_ptr = nullptr;
};

#endif 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值