Direct3D COM 接口的发布顺序重要吗?

Does the order in which Direct3D COM interfaces released matter?

例如考虑这个结构

struct Foo
{
    ComPtr<ID3D11Texture2D> back_buffer;
    ComPtr<IDXGISwapChain> swap_chain;
    ComPtr<ID3D11DeviceContext> device_context;
    ComPtr<ID3D11Device> device;
}

此处调用 release() 的顺序与创建这些 COM 对象的顺序相同。它会引起任何问题吗?

一般来说,COM 对象的释放顺序严格来说应该无关紧要。也就是说,Direct3D 在生命周期中不使用严格的 COM 规则。一旦您释放了对 Direct3D 设备的最后一个引用,那么该设备的所有子对象都将无效,无论它们各自的引用计数是多少。

为了使清理工作更容易一些,Direct3D 调试设备中有 'object leak detection',因此在释放最终设备实例之前干净地释放所有内容会很有帮助。参见 Direct3D SDK Debug Layer Tricks and DXGI Debug Device

请记住,对象到对象的引用也可以使计数保持活动状态,并且 Direct3D 使用 'deferred destruction'。因此,'clean exit' 需要在您取消绑定所有对象后刷新:

m_d3dContext->ClearState();
m_d3dContext->Flush();
// Release all your objects except the device
// Final release of the device here

You don't have to use such a clear & flush for cleanup with Direct3D 11, but you'll end up with a lot of 'false reports' of live objects by the Debug Layer if you don't Flush after unbinding. With Direct3D 12, you have to ensure the GPU is idle before you start releasing things to get a clean exit.