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

3

7

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

Paintbrush answered 17/6, 2013 at 19:37 Comment(0)
T
4

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.

Ten answered 17/6, 2013 at 19:46 Comment(2)
In your opinion, if I had to choose one of the two, should I do value or const&? - I mean this more from a stylistic / best-practice point of view.Paintbrush
const&. You switch to pass by val only to avoid an aliasing problem, and for ComPtr regular usage I doubt we could have sensible examples. But if you have a function also getting a ComPtr<relatedtype> by nonconst& you may switch to value.Ten
S
3

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.

Stated answered 17/6, 2013 at 19:49 Comment(1)
Thanks for the const reference tip, I'll change that.Paintbrush
P
2

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

Presentday answered 18/6, 2013 at 21:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.