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?

非常感谢。

对于 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_ptr 更可取。 auto_ptr所有权转让副本语义被发现只是麻烦。

最新更新