How to pass unique_ptr <T> instead of the pointer parameter raw * output *?

I have an existing function in an external library that 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 memory when I finish.

Obviously, I would like to keep this result in unique_ptr<MyThing>and avoid the manual delete.

I could create a temporary raw pointer for use with an API call and pass it to the constructor for unique_ptr;

MyThing* tempPtr;
CreateTheThing(tempPtr);
unique_ptr<MyThing> realPtr = unique_ptr<MyThing>(tempPtr);

Is there a more direct method than this? One that does not require a temporary raw pointer? Ideally, is there a method unique_ptrthat expands its internal pointer in a way that can work directly with the method CreateTheThing?

unique_ptr<T>::get()does not allow this, as far as I know. The returned pointer is not a reference to an internally used pointer.

+6
source share
3 answers

Is there a more direct method than this? One that does not require a temporary raw pointer?

No no.

, unique_ptr, , CreateTheThing? unique_ptr::get() , .

. std::unique_ptr, unique_ptr::get() const, .

, std::unique_ptr::reset() , .

: API free(), std::unique_ptr.

+9

( ), :

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); }
};

:

std::unique_ptr<MyThing> u;
CreateTheThing(Wrapper(u));
+7

If you use this function often, you can put the conversion in the function.

It would be best to change the API, but that might work as well.

inline std::unique_ptr<MyThing> CreateTheThing()
{
  MyThing* p;
  if (CreateTheThing(p))
  {
    return std::unique_ptr<MyThing>(p);
  }
  return std::unique_ptr<MyThing>();
}
+3
source

All Articles