0
点赞
收藏
分享

微信扫一扫

C++ sharedPtr实现

修炼之士 2022-03-11 阅读 58
#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 = p1;
	shared_ptr<int> p3(new int(3));
	
    cout << "Hello Rainy";
    return 0;
}
举报

相关推荐

C++实现扫雷

c++ hash实现

C++ 实现复数

C++实现 Topsis

LRU C++实现

0 条评论