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

Mar*_*cus 3 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;
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

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

这是正确的方法,还是我应该更好/更安全地使用semothing?

非常感谢.

Ben*_*igt 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))
  {
  }
};
Run Code Online (Sandbox Code Playgroud)

此外,std::unique_ptr(如果你有一个C++ 11编译器)或boost::scoped_ptr两者都更好std::auto_ptr. auto_ptr转让所有权复制语义已被发现只是麻烦.

  • @Marcus:然后我仍然会看看Boost.Move并编写自己的`unique_ptr`,但*请*只是废除`auto_ptr`. (2认同)