I have a pre-existing function in an external library, which looks like this;
bool CreateTheThing(MyThing *& pOut);
In short; I give it a raw pointer (by reference), and the function allocates memory and assigns my pointer to the newly-allocated object. When the function returns, it is my responsibility to free the memory, when I'm done.
Obviously, I'd like to store this result into a unique_ptr<MyThing>
, and avoid the manual delete
.
I could create a temporary raw pointer to use with the API call, and pass it into the constructor for the unique_ptr
;
MyThing* tempPtr;
CreateTheThing(tempPtr);
unique_ptr<MyThing> realPtr = unique_ptr<MyThing>(tempPtr);
Is there a more direct method than this? One which doesn't require a temporary raw pointer? Ideally, there would be a method of unique_ptr
which exposes its internal pointer in a way that could work directly with the CreateTheThing
method?
unique_ptr<T>::get()
does not allow this, to my knowledge. The pointer it returns is not a reference to the internally-used pointer.
You can save one line of code (potentially many times) by writing many lines of code once:
class Wrapper
{
std::unique_ptr<MyThing> &u;
MyThing *p;
public:
Wrapper(std::unique_ptr<MyThing> &u) : u(u), p() {}
operator MyThing* & ()
{ return p; }
~Wrapper()
{ u.reset(p); }
};
Usage:
std::unique_ptr<MyThing> u;
CreateTheThing(Wrapper(u));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With