shared_ptr
不能将两个shared_ptr对象与同一个指针关联,因为构造函数是不会增加计数值的,但是可以将一个shared_ptr赋值给另外一个shared_ptr,拷贝构造和operator=重载会将计数+1的
shared_ptr实现:
#include<iostream>
using namespace std;
template <typename T>
class Shared_ptr
{
private:
int* cnt;
T* ptr_;
public:
Shared_ptr(T* ptr);
~Shared_ptr();
Shared_ptr(Shared_ptr<T>& s);
Shared_ptr<T>& operator=(Shared_ptr<T>& s);
T* get(){return ptr_;}
};
template <typename T>
Shared_ptr<T>::Shared_ptr(T* ptr):ptr_(ptr){
if(ptr_==nullptr)
{
cnt=new int(0);
}
else
{
cnt=new int(1);
}
}
template <typename T>
Shared_ptr<T>::~Shared_ptr(){
(*cnt)--;
if(*cnt==0)
{
delete cnt;
delete ptr_;
}
}
template <typename T>
Shared_ptr<T>::Shared_ptr(Shared_ptr<T>& s){
if(*this!=&s){
this->cnt=s.cnt;
this->ptr_=s.ptr_;
(*cnt)++;
}
}
template <typename T>
Shared_ptr<T>& Shared_ptr<T>::operator=(Shared_ptr<T>& s){
if(this!=&s){
this->cnt=s.cnt;
this->ptr_=s.ptr_;
this->cnt++;
}
return *this;
}
int main(){
int* a=new int(1);
Shared_ptr<int> ptr1(a);
{
Shared_ptr<int> ptr2(a);
}
ptr1.get();
}