构造函数体中的auto_ptr成员初始化(不在初始化列表中)

时间:2012-06-03 15:58:59

标签: c++ constructor auto-ptr

我想知道在我的类的构造函数中初始化auto_ptr成员的正确方法。 我的类有2个(或更多)不同类型的auto_ptr实例。其中一个的初始化取决于第一个初始化的结果。

澄清一下,这就是我正在做的事情:

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;
    }
  }
};

该示例有点重复但是要强制实现2个auto_ptr实例之间的依赖关系。 我决定在构造函数体中创建一个本地auto_ptr,并在我初始化它时立即将其托管实例的所有权转移给类成员。

这是正确的方法吗?或者我应该使用更好/更安全的semothing?

非常感谢。

1 个答案:

答案 0 :(得分:6)

对于 ctor-initializer-list 中的复杂初始化规则,请使用辅助函数:

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))
  {
  }
};

此外,std::unique_ptr(如果您有C ++ 11编译器)或boost::scoped_ptr都优于std::auto_ptrauto_ptr转让所有权复制语义已被发现只是麻烦。