tags:

views:

134

answers:

2

Hello,

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?

+3  A: 

Related question: http://stackoverflow.com/questions/321068/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.

Fred Larson
It is an option. But I'd prefer not to use pairs and structs if I could.
FireAphis
Timbo's answer should work if you prefer return parameters. Personally, I dislike return parameters and avoid then whenever possible.
Fred Larson
+3  A: 

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.

Timbo
As I understand the caller will remain the "owner" of the pointers. Looks exactly what I need. I will try it promptly.
FireAphis