#pragma once
#include <atomic>

class IVrUnkown
{
public:
	IVrUnkown() :m_nRefCount(1) {}
	virtual ~IVrUnkown() {}

	/// 引用 +1
	void AddRef()
	{
		std::atomic_fetch_add(&m_nRefCount, 1);
	}

	/// 引用 -1 
	int Release()
	{
		int nRef = std::atomic_fetch_sub(&m_nRefCount, 1); //atomic_fetch_sub 执行返回原值
		if (1 == nRef)  //默认是1 减到1时删除
		{
			delete this;
		}
		return nRef - 1;
	}

private:
	std::atomic<int>		m_nRefCount;	//计数
};

template<typename T>
void VrSafeAddRef(T* pObj)
{
	if (pObj)
	{
		pObj->AddRef();
	}
}

template<typename T>
void VrSafeReleaseRef(T** pObj)
{
	if (pObj && *pObj)
	{
		T* p = *pObj;
		if(0 == p->Release())
		{
			*pObj = nullptr;
		}
	}
}
