c++c++11unique-ptr

Can I store a function's output parameter into a unique_ptr?


I have the following code:

class Thing
{};

void fnc(Thing** out)
{
    *out = new Thing();
};

Where fnc returns a new instance of Thing via output parameter. Normally I'd use it as follows:

int main()
{
    Thing* thing;
    fnc(&thing);  
}

Can I put the returned object in a std::unique_ptr instead?

int main()
{
    std::unique_ptr<Thing> uniqueThing;
    fnc(???);
}

Solution

  • You should store the raw pointer in the unique_ptr so that the unique_ptr takes ownership:

    Thing* thing;
    fnc(&thing);
    std::unique_ptr<Thing> thing_unique (thing);