as the MSDN is not very specific at this point: in my application I create a texture by calling CreateTexture2D().
On success, do I have to release the created texture? If yes, how?
Thanks!
TL;DR: This is documented on MSDN in this article: Programming DirectX with COM
Direct3D uses COM reference-counting for lifetime management.
All the objects are derived from IUnknown
and when they are created have a refcount of 1.
When you call Release
it decrements the refcount. Once the refcount is 0, the object is eligible for cleaning up all it's memory and resource use. For performance reasons, Direct3D uses deferred destruction so typically all these objects are cleaned up a frame or two later.
Once the "external" refcount is 0, the Direct3D Runtime will deal with cleaning it up. You don't have to do anything else. If you want to force all deferred destruction, you can use
ID3D11DeviceContext::Flush
, but you shouldn't do it often as it severely impacts performance.
If you want to have more than one pointer reference the same object, you call AddRef
to increment it's refcount.
For Direct3D 10, 11, and 12, there is a slight modification of the COM lifetime rules. Specifically, if a "device" hits a refcount of 0, then all "device child objects" created from that device are invalid even if their refcount is non-zero.
For Direct3D 10, 11, and 12, if you 'bind' an object to the rendering pipeline, this does not increment the refcount. You have to ensure the object remains valid until the rendering is complete. See Reference Counting (Direct3D 10).
For C++ development, the strong recommendation is to use a COM smart-pointer of some kind to automatically increment/decrement refcounts as needed. Options here include:
Microsoft::WRL::ComPtr
**winrt::com_ptr
wil::com_ptr
For completeness there is also:
CComPtr
(WRL is basically "ATL 2.0", and ATL is only installed with Visual Studio as an opt-in feature)_com_ptr_t
(a half-hearted attempt, so not a great choice)** = This is my preference currently since it's available in the Windows 8.0 SDK or later and works for Win32 desktop, UWP, and Xbox. See DirectX Tool Kit Wiki: ComPtr for reasoning and examples.
See also MSDN: Managing Object Lifetimes Through Reference Counting and Wikipedia: Reference counting