自己实现的简易版C++智能指针shared_ptr
#include <iostream>
using namespace std;
template<class T>
class Shared_ptr{
private:
T* m_ptr;
int* m_use_count;
public:
Shared_ptr(T* ptr=nullptr):m_ptr(ptr){
cout<<"Constructor"<<endl;
m_use_count=ptr==nullptr?new int(0):new int(1);
}
Shared_ptr(const Shared_ptr& other):m_ptr(other.m_ptr),m_use_count(other.m_use_count){
cout<<"Copy Constructor"<<endl;
++(*other.m_use_count);
}
Shared_ptr& operator=(const Shared_ptr& other) {
cout<<"Copy assignment"<<endl;
if (--(*m_use_count) == 0)
{
delete m_ptr;
delete m_use_count;
m_ptr=nullptr;
m_use_count=nullptr;
}
m_ptr=other.m_ptr;
m_use_count=other.m_use_count;
++(*other.m_use_count);
return *this;
}
Shared_ptr(Shared_ptr&& other){
cout<<"Move Constructor"<<endl;
m_ptr=other.m_ptr;
m_use_count=other.m_use_count;
other.m_use_count=nullptr;
other.m_ptr=nullptr;
}
Shared_ptr& operator=(Shared_ptr&& other) {
if (--*m_use_count == 0)
{
delete m_ptr;
delete m_use_count;
m_ptr=nullptr;
m_use_count=nullptr;
}
cout<<"Move assignment"<<endl;
m_ptr=other.m_ptr;
m_use_count=other.m_use_count;
other.m_ptr=nullptr;
other.m_use_count=nullptr;
return *this;
}
~Shared_ptr(){
cout<<"Destructor"<<endl;
if(m_ptr&&m_use_count&&--(*m_use_count)==0){
delete m_ptr;
delete m_use_count;
m_ptr=nullptr;
m_use_count=nullptr;
}
}
int get_use_count(){
return *m_use_count;
}
};
int main(int argc,char** argv)
{
Shared_ptr<int> p(new int(10));
auto q=p;
cout<<q.get_use_count()<<" "<<p.get_use_count()<<endl;
auto t(move(q));
cout<<t.get_use_count()<<endl;
return 0;
}