Search code examples
c++auto-ptr

Returning multiple auto_ptrs from a function


I have a function that allocates two variables on the heap and returns them to the caller. Something like this:

void Create1(Obj** obj1, Obj** obj2)
{
    *obj1 = new Obj;
    *obj2 = new Obj;
}

Usually, in similar cases, when I have a function with one variable I use the "source" trick with auto_ptr:

auto_ptr<Obj> Create2()
{
    return new Obj;
}

I would like to rewrite Create1 using auto_ptr but not sure how to do it. As far as I understand I cannot return auto_ptr by reference, am I right? So is it possible at all?


Solution

  • You can assign to a std::auto_ptr by calling its reset method:

    void f( std::auto_ptr<Obj>& pObj1, std::auto_ptr<Obj>& pObj2 )
    {
        pObj1.reset( new Obj );
        pObj2.reset( new Obj );
    }
    

    The reset call will properly delete whatever the auto_ptr was pointing to before.