智能指针(四)之shared_ptr

1.auto_ptr:采用管理权转移的方法 ,防止拷贝后析构释放同一块内存

2scoped_ptr:禁止拷贝和赋值

3shared_ptr:要想使用拷贝构造,赋值运算符,但是析构的时候不会报错,我们想到了使用引用计数的方法,使得析构函数只释放一次内存。每次构造时,使引用计数count++,析构时看count是否为一,若不为一--count;若为宜则释放空间。

代码实现

template<class T>
class Sharedptr
{
public:
	Sharedptr(T* ptr = NULL)
		:_ptr(ptr)
		, _count(NULL)
	{
		if (ptr != NULL)
		{
			_count = new int(1);
		}
	}
	Sharedptr(const Sharedptr& s)//拷贝构造
		:_ptr(s._ptr)
		, _count(s._count)
	{
		if (s._ptr != NULL)
		{
			++(*_count);
		}
	}
	Sharedptr &operator= (const Sharedptr& s)
	{
		if (_ptr != s._ptr)
		{
			Sharedptr tmp(s);
			std::swap(_ptr,tmp._ptr);
			std::swap(_count, tmp._count);
		}
		return *this;
	}
	~Sharedptr()
	{
		if (_count!=NULL && *_count == 1)
		{
			delete _ptr;
			delete _count;
			_ptr = NULL;
			_count = NULL;
		}
		else
			--(*_count);
	}
private:
	T* _ptr;
	int *_count;
};

int main()
{
	Sharedptr<int> s1(new int(10));
	Sharedptr<int> s2(new int(20));
	Sharedptr<int> s3(s1);
	s2 = s1;
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/audience_fzn/article/details/78510796