#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;
}
C++ sharedPtr实现
于 2022-03-06 23:37:44 首次发布