Gabriel C.
Gabriel C.

Reputation: 127

Should I call Release on a ID3D10Device interface after using CreateTexture2D? why?

I've this code in a directx10 project.

ID3D10Texture2D *depthStencilBuffer;
UINT a = m_device->Release();
if(FAILED(hr = m_device->CreateTexture2D( &descDepth, NULL, &depthStencilBuffer ))) {
    DXGI_D3D10_ErrorExit(hr, L"CreateTexture2D");
    return hr;
}
a = m_device->Release();

Now if I stop the debugger at the third line and check the value of a it says 2. And when I stop it at the line after the last one it says 3. I can't understand why. Is the CreateTexture2D function adding references to the ID3D10Device interface? And apparently it's not even adding one reference but two of them since Release() decrements one. My problem is the documentation for ID3D10Device::CreateTexture2D doesnt specify it adds references to the ID3D10Device object. Same goes for ID3D10Device::CreateRenderTargetView for instance. How am I supposed to guess when to call Release?

Upvotes: 0

Views: 626

Answers (1)

Stephen Quan
Stephen Quan

Reputation: 26096

I don't have the ability to have the DirectX SDK installed atm to test this, but, in general principals, when it comes to COM you should follow the COM rules and trust that other objects follow the rules too.

i.e. you shouldn't know the implementation of Texture2D but you should trust that if it needs add references to device, that it will also remove them when it is done. You shouldn't be attempting to make additional calls to Release().

Your code should read:

ID3D10Texture2D *depthStencilBuffer = NULL;
if(FAILED(hr = m_device->CreateTexture2D( &descDepth, NULL, &depthStencilBuffer ))) {
    DXGI_D3D10_ErrorExit(hr, L"CreateTexture2D");
    return hr;
}
depthStencilBuffer->Release();
depthStencilBuffer = NULL;

i.e. you should expect that the call returns a texture2d with a reference count of 1, this is all you need to know. When you're done, you should call release only on the depthStencilBuffer and expect it to clean up itself entirely. If during the implementation the stencil buffer needed references to the device, you should trust that it will also call release on those references correctly.

Upvotes: 2

Related Questions