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.
For complex initialization rules inside the ctor-initializer-list, use a helper function:
Also,
std::unique_ptr
(if you have a C++11 compiler) orboost::scoped_ptr
are both preferable tostd::auto_ptr
.auto_ptr
transfer-of-ownership copy semantics have been found to be nothing but trouble.