Reputation: 6790
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?
Upvotes: 2
Views: 699
Reputation: 28050
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.
Upvotes: 4
Reputation: 62053
Related question: Returning multiple values from a C++ function
I wouldn't expect problems using auto_ptr in a pair or tuple. Returning a struct containing a couple of auto_ptr members should work too.
Upvotes: 4