I've been tossing around ComPtrs in my code because I need them here and there but I've been doing it like so:
HRESULT Material::Initialize(aiMaterial* pMaterial,
Microsoft::WRL::ComPtr<ID3D11Device1> & d3dDevice,
Microsoft::WRL::ComPtr<ID3D11DeviceContext1> & d3dContext)
Is this completely negating the ref counting benefit of a ComPtr? Should I just do a pass by value (no &) instead?
Thanks you for reading
ComPtr automatically maintains a reference count for the underlying interface pointer and releases the interface when the reference count goes to zero.
Microsoft::WRL::ComPtr is a C++ template smart-pointer for COM objects that is used extensively in Windows Runtime (WinRT) C++ programming.
Go Up to COM Interfaces. An interface pointer is a pointer to an object instance that points, in turn, to the implementation of each method in the interface. The implementation is accessed through an array of pointers to these methods, which is called a vtable.
It's perfectly okay and preferred to pass it around as const&.
Pass by value is acceptable from semantics standpoint, not that much from performance, as passing so causes bumping the refcount up and down, and both are "interlocked" operations with serious consequences. And we gain nothing in return.
The benefit of ComPtr is that it allows proper matching of Release calls, that is all too easy to mess up, and even if it was easy the mess of the code it takes is unpleasant.
No, you're doing the right thing. The callee doesn't have to modify the reference count unless it needs to hold onto the interface for access after the call. Incrementing and decrementing the reference count is not free - it's a virtual call plus an interlocked increment or decrement - so you get better performance anyway. You should use a const reference though - or even just pass down a raw pointer.
Yep in my DirectX code, I arrange my engine to make it clear which object have the authority to manage the lifetime of a DirectX COM object. Then I pass it as raw pointer to methods that need them (I avoid to keep member variables track DX objects as much as possible).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With