C++ sharedPtr实现

#include <iostream>
using namespace std;

template <typename T>
class shared_ptr {
private:
	// 引用计数指针与模板指针
    int* count;
	T* ptr;
public:
    // 构造函数,初始化引用计算与模板指针
	shared_ptr(T* p) : count(new int(1)), ptr(p) {
		cout << "调用构造函数" << endl;
	}
	// 复制构造函数,引用计算+1
	shared_ptr(shared_ptr<T>& other) : count(&(++*other.count)), ptr(other.ptr){
		cout << "调用复制构造函数" << endl;
	}
	// 指针运算符
	T* operator->() {
		cout << "调用指针运算符" << endl;
	    return ptr; // 返回模板指针
	}
    // 解引用运算符
	T& operator*() {
		cout << "调用解引用运算符" << endl;
	    return *ptr; // 返回对象本身
	}
	// 赋值操作符重载
	shared_ptr<T>& operator=(shared_ptr<T>& other) {
	    ++*other.count;
		if (this->ptr && --*this->count == 0) {
			 cout << "清理原智能指针" << endl;
		     delete count;
			 delete ptr;
		}
		cout << "调用赋值操作符" << endl;
		this->ptr = other.ptr;
		this->count = other.count;
		return *this;
	}
	// 析构函数
	~shared_ptr() {
	    if (--*count == 0) {
		    delete count;
			delete ptr;
		}
	}
	// 获取引用计数
	int getRef() {return *count;}
};

int main()
{
    shared_ptr<int> p1(new int(1));
	shared_ptr<int> p2(new int(2));
    p2 = p1;
	shared_ptr<int> p3(p1);
	
    cout << "Hello Rainy";
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值