智能指针
简单版:
#include<bits/stdc++.h>
using namespace std;
template<class T>
class shared_mptr{
// 三种构造函数:空,new,shared_mptr
shared_mptr():ptr(nullptr),count(0){} // 空指针
shared_mptr(T* p):count(new int(1)),ptr(p){}
shared_mptr(shared_mptr<T> &other):count(++(*other.count)),ptr(other.ptr){}
// 三种运算符:->,*,=
T* operator->(){return ptr}; // 不知道为什么返回值是T*,记住就行
T& operator*(){return *ptr} // 因为对类外对*ptr的修改需要影响到类内的*ptr,所以使用了引用
shared_mptr<T>& operator=(shared_mptr<T> &other){
if(this == &other) return *this;
++*other.count;
if(this->ptr && --this->count==0){ // 由于当前对象被覆盖了,所以引用计数需要减一
delete this->ptr;
delete this->count; // count也是一个栈上对象,不要忘记delete
}
this->count = ++other.count;
this->ptr = other.ptr;
return *this;
}
~shared_mptr(){
if(ptr&&--*count==0){ // 不止要判断count,还要判断ptr
delete ptr;
delete count;
}
}
int getRef() // 测试使用,可写可不写。
{
return *count;
}
private:
T* ptr;
int *count;
};