c++ 实现智能指针shared_ptr

2023-11-05

sharedPtr.h

#ifndef _sharedPtr_H__
#define _sharedPtr_H__

class sharedPtr {
public:
	sharedPtr();
	sharedPtr(int*);
	sharedPtr(const sharedPtr&);
	sharedPtr(sharedPtr&&);
	
	sharedPtr& operator=(const sharedPtr&);
	sharedPtr& operator=(sharedPtr&&);

	int& operator*();
	int useCount();

	~sharedPtr();
private:
	int* ptr;
	int* use_count;  // 引用计数
};

#endif

sharedPtr.cpp

#include "sharedPtr.h"
#include <iostream>

sharedPtr::sharedPtr() :ptr(nullptr), use_count(new int(0)) {
}

sharedPtr::sharedPtr(int* p){
	if (p == nullptr) {
		ptr = nullptr;
		use_count = new int(0);
	}
	else {
		ptr = p;
		use_count = new int(1);
	}
}

// 拷贝构造函数
sharedPtr::sharedPtr(const sharedPtr& p) {
	// 如果空指针的话 引用计数等于0
	this->ptr = p.ptr;
	this->use_count = p.use_count;
	if(p.ptr != nullptr){
		(*use_count)++;
	}
}

// 移动构造函数 移交控制权
sharedPtr::sharedPtr(sharedPtr&& p) {
	this->ptr = p.ptr;
	this->use_count = p.use_count;
	p.ptr = nullptr;
	p.use_count = nullptr;

}

sharedPtr& sharedPtr::operator=(const sharedPtr& p) {
	ptr = p.ptr;
	use_count = p.use_count;
	(*use_count)++;
	return *this;
}

sharedPtr& sharedPtr::operator=(sharedPtr&& p) {
	this->ptr = p.ptr;
	this->use_count = p.use_count;
	p.ptr = nullptr;
	p.use_count = nullptr;
	return *this;
}

int& sharedPtr::operator* () {
	return *ptr;
}

sharedPtr::~sharedPtr() {
	if (this->use_count == nullptr) {
		delete ptr;
		delete use_count;
		std::cout << "释放内存空间" << std::endl;
	}
	else {
		(*use_count)--;
		if (*(this->use_count) == 0) {
			delete ptr;
			delete use_count;
			std::cout << "释放内存空间" << std::endl;
		}
	}

}

int sharedPtr::useCount() {
	if (use_count == nullptr) {
		return 0;
	}
	return *use_count;
}

test.cpp

#include <iostream>
#include <memory>
#include "sharedPtr.h"
using namespace std;

int main()
{
    sharedPtr ptr(nullptr);
    cout << ptr.useCount() << endl;
    sharedPtr ptr1(new int(10));
    cout << *ptr1 << endl;
    cout << ptr1.useCount() << endl;

    {
        sharedPtr ptr2(ptr1);
        cout << ptr1.useCount() << endl;
    }

    sharedPtr ptr3 = ptr1;
    cout << ptr1.useCount() << endl;
    sharedPtr ptr4 = move(ptr3);
    cout << ptr1.useCount() << endl;
    cout << ptr3.useCount() << endl;
    cout << ptr4.useCount() << endl;

    //shared_ptr<int> ptr(nullptr);
    //cout << ptr.use_count() << endl;
    //shared_ptr<int> ptr1(new int(10));
    //cout << *ptr1 << endl;
    //cout << ptr1.use_count() << endl;
    //shared_ptr<int> ptr2(ptr1);
    //cout << ptr1.use_count() << endl;
    //shared_ptr<int> ptr3 = ptr2;
    //cout << ptr1.use_count() << endl;
    //shared_ptr<int> ptr4 = move(ptr3);
    //cout << ptr1.use_count() << endl;
    //cout << ptr3.use_count() << endl;
    //cout << ptr4.use_count() << endl;

    return 0;
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c++ 实现智能指针shared_ptr 的相关文章

随机推荐