对于COM对象来说使用传统指针比较麻烦,还要记得Release()防止内存泄漏,一不小心就会出现各种各样的问题。针对这种问题微软提供了对于COM对象的智能指针ComPtr,这里是官方文档https://github.com/Microsoft/DirectXTK/wiki/ComPtr
举个例子,原先的代码:
1 ID3D11Buffer* m_pVertexBuffer; 2 ID3D11Buffer* m_pIndexBuffer; 3 ID3D11InputLayout* m_pInputLayout; 4 5 ID3DX11Effect* m_pFx; 6 ID3DX11EffectTechnique* m_pTechnique; 7 ID3DX11EffectMatrixVariable* m_pFxWorldViewProj; 8 9 void HillsDemo::UnLoadContent() 10 { 11 if (m_pVertexBuffer) m_pVertexBuffer->Release(); 12 if (m_pIndexBuffer) m_pIndexBuffer->Release(); 13 if (m_pInputLayout) m_pInputLayout->Release(); 14 if (m_pTechnique) m_pTechnique->Release(); 15 if (m_pFx) m_pFx->Release(); 16 }
使用ComPtr的代码:
1 Microsoft::WRL::ComPtr<ID3D11Buffer> m_pVertexBuffer; 2 Microsoft::WRL::ComPtr<ID3D11Buffer> m_pIndexBuffer; 3 Microsoft::WRL::ComPtr<ID3D11InputLayout> m_pInputLayout; 4 5 Microsoft::WRL::ComPtr<ID3DX11Effect> m_pFx; 6 ID3DX11EffectTechnique* m_pTechnique; 7 ID3DX11EffectMatrixVariable* m_pFxWorldViewProj; 8 9 void HillsDemo::UnLoadContent() 10 { 11 m_pVertexBuffer.Reset(); 12 m_pIndexBuffer.Reset(); 13 m_pInputLayout.Reset(); 14 m_pFx.Reset(); 15 m_pTechnique = nullptr; 16 pFxWorldViewProj = nullptr; 17 }