Search code examples
c++auto-ptr

Returning a new object along with another value


I want to return two values, one of which is a new object. I can do this using std::pair:

class A {
//...
};

std::pair<A*, int> getA()
{
   A* a = new A;
   //...
} 

To make the code exception-safe, I would like to do:

std::pair<std::auto_ptr<A>, int> getA()
{
    std::auto_ptr<A> a(new A); 
    //...
} 

But this won't compile as the auto_ptr cannot be copied without modifying the auto_ptr being copied. Ok, this means auto_ptr does not compose well like other types (in one more way). What is a good way of returning a new object in this case?

One alternative is to return a shared_ptr and another is an inout reference. But I am looking for some other alternative. I can do something like:

class AGetter
{
    void getAExecute()
    {
         //...
         // set a_ and i_
    }
    std::auto_ptr<A> getA() const
    {
         return a_.release();
    }
    int getInt() const
    {
         return i_;
    }
    private:
    std::auto_ptr<A> a_;
    int i_;
};

Is there a better way?


Solution

  • Just create a new class and return that class

    class Result
    {
       A* a;
       int i;
    public:
       Result( A*a, int i ) : a(a), i(i) {
       }
       ~Result() { 
          delete a; 
       }
       // access functions, copy constructor, ...
    };
    
    Result getA() {
       //...    
       return Result(new A, intValue);  
    }