2

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?

FireAphis
  • 6,650
  • 8
  • 42
  • 63

2 Answers2

4

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.

Community
  • 1
  • 1
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
4

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
  • 27,472
  • 11
  • 50
  • 75
  • As I understand the caller will remain the "owner" of the pointers. Looks exactly what I need. I will try it promptly. – FireAphis Jul 30 '09 at 14:30