Search code examples
c++pointersunique-ptr

Passing a unique pointer's pointer to a function that takes a double pointer


I have a function that effectively does this

void foo(Class** c)
{
    // memory checks and stuff
    (*c) = new Class();
    // more stuff
}

I cannot change this function. To call this function I have to do something like this.

Class* c = nullptr;
foo(&c);
if (c)
{
    // stuff
}
delete c;

I would very much prefer to use a std::unique_ptr rather than the raw pointer. However, I don't know how to get the address of the internal pointer. The listing below does not compile, obviously, because I'm trying to take the address of an rvalue.

std::unique_ptr<Class> c = nullptr;
foo(&(c.get()));
if (c)
{
    // stuff
}

I realize I could make the raw pointer as well as the unique pointer, call the function, then give the raw pointer to the unique pointer, but I would prefer to not. Is there a way to do what I want to do?


Solution

  • Create a wrapper around foo:

    std::unique_ptr<Class> foo()
    {
        Class* c = nullptr;
        foo(&c);
        return std::unique_ptr<Class>(c);
    }