C++自定义实现共享指针shared_ptr

自定义数据类型

class stu {
private:
	string m_name;
	int m_age;
public:
	stu(string name, int age) {
		m_name = name;
		m_age = age;
	}
	~stu() {}

	void showInfo() {
		cout <<"姓名:" << this->m_name<<"年龄:" << this->m_age << endl;
	}
};

定义共享指针shared_ptr

template <typename T>
class mysharedPtr {
public:
	//构造函数
	mysharedPtr(T* ptr = nullptr) {
		m_ptr = ptr;
		m_count = new int(0);//申请存放引用计数值的内存
		++(*m_count);//引用计数+1
	}
	//析构函数
	~mysharedPtr() {
		--(*m_count);
		if ((*m_count) == 0) {
			delete m_count;
			m_count = nullptr;
			delete m_ptr;
			m_ptr = nullptr;
		}
	}
	//拷贝构造函数
	mysharedPtr(const mysharedPtr& other) {
		m_ptr = other.m_ptr;
		m_count = other.m_count;
		++(*m_count);
	}

	//赋值拷贝构造函数
	mysharedPtr operator=(const mysharedPtr& other) {
		++(*other.m_count);
		--(*m_count);
		if ((*m_count) == 0) {
			delete m_count;
			m_count = nullptr;
			delete m_ptr;
			m_ptr = nullptr;
		}
		m_count = other.m_count;
		m_ptr = other.m_ptr;
		return *this;//返回对象本身
	}
	T* operator->() {
		return m_ptr;
	}


private:
	T* m_ptr;
	int* m_count;
};

主函数

#include<iostream>
#include<stdlib.h>
using namespace std;
int main() {
	mysharedPtr<stu>ptr1 (new stu("zhangsan", 20));
	ptr1->showInfo();
	mysharedPtr<stu>ptr2(ptr1);
	mysharedPtr<stu>ptr3 = ptr1;
	ptr2->showInfo();
	ptr3->showInfo();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木星健谈能手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值