auto_ptr member initialization in constructor body (not in initializators list)

auto-ptr, c++, constructor

Solution

For complex initialization rules inside the ctor-initializer-list, use a helper function:

class Holder {
private:
  std::unique_ptr<C1> c1;
  std::unique_ptr<C2> c2;

  static C2* c2_init_helper(/* const? */ C1& the_c1)
  {
    int const x = the_c1->getGeneratedValue1();
    int const y = the_c1->getGeneratedValue2();

    if (x > 0) {
      if (y > 0) return new C2(true, 10);
      return new C2(false, 20);
    }
    if (y > 0) return new C2(false, 30);
    return new C2(false, 0);
  }

public:
  Holder() :
    c1(new C1()),
    c2(c2_init_helper(*c1))
  {
  }
};

Also, `std::unique_ptr` (if you have a C++11 compiler) or `boost::scoped_ptr` are both preferable to `std::auto_ptr`. `auto_ptr` transfer-of-ownership copy semantics have been found to be nothing but trouble.

Problem

I'm wondering the right way to initialize an auto_ptr member in the constructor of my class. My class has 2 (or more) auto_ptr instances of different types. And the initialization of one of them deppends on results of the initialization of the first. To clarify, this is what I'm doing: ``` class C1 { ... } class C2 { ... } class Holder { private: auto_ptr<C1> c1; auto_ptr<C2> c2; public: Holder() : c1(new C1()), c2(NULL) { int x = this->c1->getGeneratedValue1(); int y = this->c1->getGeneratedValue2(); if (x > 0 && y > 0) { auto_ptr<C2> lC2(new C2(true, 10)); this->c2 = lC2; } else if (x > 0) { auto_ptr<C2> lC2(new C2(false, 20)); this->c2 = lC2; } else if (y > 0) { auto_ptr<C2> lC2(new C2(false, 30)); this->c2 = lC2; } else { auto_ptr<C2> lC2(new C2(false, 0)); this->c2 = lC2; } } }; ``` The example is a little repetitive but that to enforce the dependence between the 2 auto_ptr instances. I decided to create a local auto_ptr in the constructor body and transfer the ownership of its managed instance to the class member as soon as I initialize it. Is that the right way to do that or should I use semothing better/safer? Thanks very much.

Original source