Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Is using auto_ptr references as out variables idiomatic?

Suppose I want to write factory method that is supposed to allocate heterogeneous objects on the heap and return them to the caller. I am thinking of designing the API like this:

bool MakeEm(auto_ptr<Foo>& outFoo, auto_ptr<Bar>& outBar) {
  ...
  if (...) {
    return false;
  }
  outFoo.reset(new Foo(...));
  outBar.reset(new Bar(...));
  return true;
}

This allows a caller to do this:

auto_ptr<Foo> foo;
auto_ptr<Bar> bar;
MakeEm(foo, bar);

My question is: "Is this idiomatic? If not, what is the right way to do this?"

The alternative approaches I can think of include returning a struct of auto_ptrs, or writing the factory API to take raw pointer references. They both require writing more code, and the latter has other gotchyas when it comes to exception safety.

like image 930
Dilum Ranatunga Avatar asked Dec 20 '25 06:12

Dilum Ranatunga


1 Answers

Asking of something is idiomatic can get you some very subjective answers. In general, however, I think auto_ptr is a great way to convey ownership, so as a return from a class factory - it's probably a Good Thing. I would want to refactor this, such that

  1. You return one object instead of 2. If you need 2 objects that are so tightly coupled they cannot exist without each other I'd say you have a strong case for is-a or has-a refactoring.
  2. This is C++. Really ask yourself if you should return a value indicating success, forcing the consumer of your factory to have to check every time. Throw exceptions or pass exceptions from the constructors of your classes in the factory. Would you ever want to be OK with false and try to operate on uninitialized auto_ptr's?
like image 155
Josh Avatar answered Dec 22 '25 18:12

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!