我想知道在我的类的构造函数中初始化 auto_ptr 成员的正确方法。 我的类(class)有 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
所有权转移拷贝语义被发现只是麻烦。
关于c++ - 构造函数体中的 auto_ptr 成员初始化(不在初始化器列表中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10871781/