简体   繁体   中英

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

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? Ie how do I pass a smart pointer for the parameter _Out_ IXAudio2 **ppXAudio2

Any Help will be much appreciated.

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. eg ATL's CComPtr . If you have access to one of these, you could use it instead of rolling your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM