Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass unique_ptr<T> in place of a raw *output* pointer parameter?

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.

like image 933
BTownTKD Avatar asked Jun 28 '17 12:06

BTownTKD


1 Answers

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));
like image 127
Angew is no longer proud of SO Avatar answered Sep 17 '22 21:09

Angew is no longer proud of SO