C++智能指针——自定义简单智能指针

//引用计数 
class FRefCounter
{
public:
	FRefCounter()
		:SharedCount(0)
		, WeakCount(0)
	{

	}

	int SharedCount;

	int WeakCount;
};
template<class T>
class FWeakPtr;

template<class T>
class FSharedPtr
{

	friend class FWeakPtr<T>;
public:


	FSharedPtr(T* InInstance = NULL)
		:Ptr(InInstance)
	{
		Count = new FRefCounter();
		if (InInstance)
		{
			Count->SharedCount = 1;
		}
	}


	FSharedPtr(FSharedPtr<T>& InInstance)
	{
		this->Ptr = InInstance.Ptr;
		InInstance.Count->SharedCount++;
		this->Count = InInstance.Count;
	}



	FSharedPtr(FWeakPtr<T>& InInstance)
	{
		this->Count = InInstance.Count;
		this->Count->SharedCount++;
		this->Ptr = InInstance.Ptr;
	}


	FSharedPtr<T>& operator=(FSharedPtr<T>& InInstance)
	{
		if (this != &InInstance)
		{
			Release();
			InInstance.Count->SharedCount++;
			this->Count = InInstance.Count;
			this->Ptr = InInstance.Ptr;
		}

		return *this;
	}

	FSharedPtr<T>& operator=(FWeakPtr<T>& InInstance)
	{
		if (this->Ptr!= InInstance.Ptr)
		{
			Release();
			this->Count = InInstance.Count;
			this->Count->SharedCount++;
			this->Ptr = InInstance.Ptr;
		}
	
	}



	T* operator*()
	{
		return *Ptr;
	}

	T* operator->()
	{
		return Ptr;
	}


	void Release()
	{

		Count->SharedCount--;

		if (Count->SharedCount >= 0)
		{

			if (Count->SharedCount < 1)
			{
				if (Count->WeakCount < 1)
				{
					delete Count;//弱指针也是需要判断 告诉弱指针 我们智能指针的情况
					Count = nullptr;
				}


				delete Ptr;
				Ptr = nullptr;

			}
		}
	}



	~FSharedPtr()
	{
		Release();
	}


private:

	T* Ptr;

	FRefCounter* Count;
};

template<class T>
class FWeakPtr
{
	friend class FSharedPtr<T>;

public:

	FWeakPtr()
		:Ptr(nullptr)
		, Count(nullptr)
	{

	}

	FWeakPtr(FSharedPtr<T>& InInstance)
		:Ptr(InInstance.Ptr)
		, Count(InInstance.Count)
	{
		Count->WeakCount++;

	}

	FWeakPtr<T>& operator=(FWeakPtr<T>& WP)
	{
		if (WP != this)
		{
			Release();
			Count = WP.Count;

			Ptr = WP.Ptr;
			Count->WeakCount++;
		}

		return *this;

	}

	FWeakPtr<T>& operator=(FSharedPtr<T>& SP)
	{
		Release();
		Count = SP.Count;

		Ptr = SP.Ptr;

		Count->WeakCount++;

		return *this;

	}

	FSharedPtr<T> Pin()
	{
		FSharedPtr<T> SP(*this);
		return SP;
	}

	bool IsVaild()
	{
		if (Count)
		{
			if (Count->WeakCount > 0)
			{
				return true;
			}
		}
		return false;
	}


	void Release()
	{
		if (Count)
		{
			Count->WeakCount--;
			if (Count->WeakCount<1&& Count->SharedCount<1)
			{
				delete Count;
				Count = nullptr;
			}
		}
	}

	~FWeakPtr()
	{
		Release();
	}

private:

	T* Ptr;

	FRefCounter* Count;

};




class FTestPtr
{
public:
	FTestPtr()
	{
		cout << "FTestPtr" << endl;
	}


};

int main()
{


	FSharedPtr<FTestPtr> TestPtr(new FTestPtr());
	FSharedPtr<FTestPtr> TestPtr2(TestPtr);
	FSharedPtr<FTestPtr> TestPtr3 = TestPtr2;

	FWeakPtr<FTestPtr> TestPtr4 = TestPtr3;
	FWeakPtr<FTestPtr> TestPtr5(TestPtr3);
	TestPtr5.Pin();



	return 0;
}

你可能感兴趣的:(C++智能指针,c++,开发语言)