智能指针share_ptr简单的写法

#include 
using namespace std;

template 
class SmartPtr
{
public:
	SmartPtr(T *p);
	~SmartPtr();
	SmartPtr(const SmartPtr &orig);
	SmartPtr& operator=(const SmartPtr &rhs);
private:
	T *ptr;
	int *use_count;
};

template
SmartPtr::SmartPtr(T *p) :ptr(p)
{
	try
	{
		use_count = new int(1);
	}
	catch (...)
	{
		delete ptr;
		ptr = nullptr;
		use_count = nullptr;
		exit(1);
	}
}

template
SmartPtr::~SmartPtr()
{
	if (--(*use_count)==0)
	{
		delete ptr;
		delete use_count;
		ptr = nullptr;
		use_count = nullptr;
		cout << "Destructor" << endl;
	}
}

template
SmartPtr::SmartPtr(const SmartPtr &orig)
{
	ptr = orig.ptr;
	use_count = orig.use_count;
	++(*use_count);
	cout << "Copy constructor" << endl;
}

template
SmartPtr& SmartPtr::operator=(const SmartPtr &rhs)
{
	++(*rhs.use_count);
	if (--(*use_count)==0)
	{
		delete ptr;
		delete use_count;
		cout << "Left side is delete" << endl;
	}
	ptr = rhs.ptr;
	use_count = rhs.use_count;
	cout << "Assignment operator overload" << endl;
	return *this;
}

 

你可能感兴趣的:(C++)