本篇文章给大家分享的是有关AddRef和Release如何进行引用计数的实现,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
interface IX : public IUnknown
{
virtual void _stdcall Fx() = 0;
};
interface IY : public IUnknown
{
virtual void _stdcall Fy() = 0;
};
interface IZ : public IUnknown
{
virtual void _stdcall Fz() = 0;
};
static const IID IID_IX = {0xec53e1de, 0x37d, 0x48f5, {0xa1, 0xee, 0x2d, 0xf5, 0xa5, 0xde, 0xf3, 0x49}}; // {EC53E1DE-037D-48f5-A1EE-2DF5A5DEF349}
static const IID IID_IY = {0x4c510b77, 0xc63a, 0x4e0f, {0xa2, 0x45, 0x7b, 0x21, 0x23, 0x12, 0x23, 0xe7}};// {4C510B77-C63A-4e0f-A245-7B21231223E7}
static const IID IID_IZ = {0xefb1f8d4, 0x674e, 0x4123, {0xa9, 0x19, 0x3c, 0x72, 0xee, 0xe8, 0x1d, 0x92}};// {EFB1F8D4-674E-4123-A919-3C72EEE81D92}
class CA : public IX,
public IY
{
public:
CA() : m_cRef(0) { }
virtual ~CA(){ }
public:
virtual HRESULT _stdcall QueryInterface(REFIID riid, __RPC__deref_out void **ppvObject);
virtual ULONG _stdcall AddRef();
virtual ULONG _stdcall Release();
virtual void _stdcall Fx() { cout<<"CA::Fx"<<endl; }
virtual void _stdcall Fy() { cout<<"CA::Fy"<<endl; }
private:
LONG m_cRef;
};
HRESULT _stdcall CA::QueryInterface(REFIID riid, __RPC__deref_out void **ppvObject)
{
if(IID_IX == riid)
{
*ppvObject = static_cast<IX*>(this);
}
else if(IID_IY == riid)
{
*ppvObject = static_cast<IY*>(this);
}
else if(IID_IUnknown == riid)
{
*ppvObject = static_cast<IX*>(this);
}
else
{
*ppvObject = NULL;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown*>(*ppvObject)->AddRef(); //对应 这五个地方需要对应起来
return S_OK;
}
ULONG _stdcall CA::AddRef()
{
InterlockedIncrement(&m_cRef);
return m_cRef;
}
ULONG _stdcall CA::Release()
{
if(InterlockedDecrement(&m_cRef) == 0)
{
delete this; //下面标记的3个Release 缺少一个则执行不到这
return 0;
}
return m_cRef;
}
IUnknown* CreateInstance()
{
IUnknown *pIUnk = static_cast<IX*>(new CA);
pIUnk->AddRef(); //对应 这五个地方需要对应起来
return pIUnk;
}
void _tmain(int argc,_TCHAR*argv[])
{
IUnknown *pIUnk = CreateInstance();
IX *pIX = NULL;
HRESULT hr = pIUnk->QueryInterface(IID_IX,(void**)&pIX);
if(SUCCEEDED(hr))
{
pIX->Fx();
pIX->Release(); //对应 这五个地方需要对应起来
}
IY *pIY = NULL;
hr = pIUnk->QueryInterface(IID_IY,(void**)&pIY);
if(SUCCEEDED(hr))
{
pIY->Fy();
pIY->Release(); //对应 这五个地方需要对应起来
}
IZ *pIZ = NULL; //没有执行到AddRef,故不需要释放
hr = pIUnk->QueryInterface(IID_IZ,(void**)&pIZ);
if(SUCCEEDED(hr))
{
cout<<"found pIZ"<<endl;
pIZ->Release();
}
pIUnk->Release(); //对应 这五个地方需要对应起来
}
以上就是AddRef和Release如何进行引用计数的实现,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。