Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I completely negating the benefit of Microsoft::WRL::ComPtr by passing it around as a reference (&)?

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

like image 411
Nico Avatar asked Jun 17 '13 19:06

Nico


People also ask

What is ComPtr in C++?

ComPtr automatically maintains a reference count for the underlying interface pointer and releases the interface when the reference count goes to zero.

What is ComPtr?

Microsoft::WRL::ComPtr is a C++ template smart-pointer for COM objects that is used extensively in Windows Runtime (WinRT) C++ programming.

What is a COM pointer?

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.


3 Answers

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.

like image 54
Balog Pal Avatar answered Sep 19 '22 12:09

Balog Pal


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.

like image 39
BitCortex Avatar answered Sep 19 '22 12:09

BitCortex


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).

like image 35
Simon Ferquel Avatar answered Sep 21 '22 12:09

Simon Ferquel