對於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 }