C++ How do I pass a smart pointer into a output parameter that will modify the pointer

922 views Asked by At

All raw pointers need to be handled with Smartpointers in a program.

But I'm having problems with this Xaudio2 call

HRESULT XAudio2Create(_Out_  IXAudio2 **ppXAudio2, _In_   UINT32 Flags,
    _In_   XAUDIO2_PROCESSOR XAudio2Processor);

My Question is how do you use smart pointers when passing it as a pointer to a pointer and is this even possible? If not how should I go about this in a smart way? I.e how do I pass a smart pointer for the parameter _Out_ IXAudio2 **ppXAudio2

Any Help will be much appreciated.

1

There are 1 answers

0
dlf On BEST ANSWER

There are two wrinkles here--first is to handle the fact that the function expects a raw pointer to a (nonconst!) raw pointer, second is to work around the fact that all the built-in smart pointers call delete on the owned pointer when what you need to do here is call its Release() method. Waiting to create the smart pointer until after the factory function returns will solve problem 1, and a custom deleter can solve problem 2. Exactly how you want to do things is up to you, but something like this should work:

IXAudio2* p = nullptr;
if(!SUCCEEDED(XAudio2Create(&p, GetFlags(), GetProcessor())))
    ; // fail
std::shared_ptr<IXAudio2> smart(p,
   [](IXAudio2* p) { p->Release(); }); // or unique_ptr with somewhat different syntax

Addendum: There have been tons of COM smart pointers written over the years that do essentially this and also call AddRef()/RemoveRef() when appropriate. e.g. ATL's CComPtr. If you have access to one of these, you could use it instead of rolling your own.