I am just learning directx. One typically creates a directx device and several other COM interfaces through a functions calls such as
ID3D11CreateDeviceAndSwapChain(.... ,& device, ...);
In all tutorial code I have seen, the com interfaces are released using something akin to
if (pointer_to_com_object) {
pointer_to_com_object->Release();
pointer_to_com_object = 0;
}
e.g. the following is taken from Tutorial07_2008 in the directx 11 tutorials from Microsoft.
if( g_pSamplerLinear ) g_pSamplerLinear->Release();
if( g_pTextureRV ) g_pTextureRV->Release();
if( g_pCBNeverChanges ) g_pCBNeverChanges->Release();
if( g_pCBChangeOnResize ) g_pCBChangeOnResize->Release();
if( g_pCBChangesEveryFrame ) g_pCBChangesEveryFrame->Release();
if( g_pVertexBuffer ) g_pVertexBuffer->Release();
if( g_pIndexBuffer ) g_pIndexBuffer->Release();
if( g_pVertexLayout ) g_pVertexLayout->Release();
if( g_pVertexShader ) g_pVertexShader->Release();
if( g_pPixelShader ) g_pPixelShader->Release();
if( g_pDepthStencil ) g_pDepthStencil->Release();
if( g_pDepthStencilView ) g_pDepthStencilView->Release();
if( g_pRenderTargetView ) g_pRenderTargetView->Release();
if( g_pSwapChain ) g_pSwapChain->Release();
if( g_pImmediateContext ) g_pImmediateContext->Release();
if( g_pd3dDevice ) g_pd3dDevice->Release();
As pointed out in answers to this question COM objects can have references to them you don’t own.
So is the above a bad way to clean up directx or do directx COM objects never have references to them you didn’t create?
I just ask because I keep seeing it done this way as I am learning.
COM objects are reference counted. When you call
Release(), you are effectively decrementing the internal reference count. If another object still owns a reference, it will not get destroyed.If some other part of the application end up having a new reference to a COM object, make sure you call
Release()when you are done with it. Carefully read documentation of methods that return references to know if you have to callRelease()or not. Usually you will have to.For instance in IDirect3DTexture9::GetSurfaceLevel documentation: