Search code examples
c++memory-managementcomdirectx

DirectX without ->Release()


The most satisfying part of writing a DIY memory manager is structuring it so you can forget about [delete] (e.g. by bundling everything into a singly allocated/deallocated buffer).

The way DirectX handles object creation means that you can't simply cast void memory into the types you want to make (can you?) and you have to rely on COM (+ remembering to [Release] local memory in every destructor) instead. Is there any way to subvert this and convince DirectX to use my pointers?

Instead of:

ID3D12Thing* thng = DirectX::CreateThing();
...
thng->Release();
thng = nullptr;

I want:

ID3D12Thing* thng = DirectX::CreateThingAt(Allocator->AlignedAlloc(sizeof(ID3D12Thing));
...
[memory emptied during shutdown]

Solution

  • TL;DR: Use a smart-pointer like ComPtr.

    I'm a big fan of std::unique_ptr and std::shared_ptr, but neither of them really correctly handle COM objects such as Direct3D interfaces which have their own built-in reference counts. A better choice is to use WRL class Microsoft::WRL::ComPtr or the C++/WinRT class winrt::com_ptr.

    Some older coders might suggest the old ATL CComPtr, but the more modern Microsoft::WRL::ComPtr is a better choice.