Nico
Nico

Reputation: 1191

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

Upvotes: 7

Views: 3282

Answers (3)

Simon Ferquel
Simon Ferquel

Reputation: 376

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

Upvotes: 2

Andromedary
Andromedary

Reputation: 3548

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.

Upvotes: 3

Balog Pal
Balog Pal

Reputation: 17163

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.

Upvotes: 4

Related Questions