It's ugly code because of the protected
variable.
I propose we reshape it up. First, let's make sure that all the ownership logic is insulated, so that it is easier to prove right.
class Base
{
public:
Base(): some(0) {} // better initialize it...
virtual ~Base() { delete some; }
void init() { delete some; some = this->initImpl(); }
private:
Base(Base const&); // no copy
Base& operator=(Base const&); // no assignment
virtual SomeType* initImpl() { return new SomeType(); }
SomeType* some;
}; // class Base
class Derived: public Base
{
virtual SomeOtherType* initImpl() { return new SomeOtherType(); }
};
It's only a first step though, because you should not try to manipulate resources directly, you're only going to leak them. So now, we take our shiny interface and reshape the implementation:
// something that you should definitely have for your base classes
class noncopyable { protected: noncopyable() {} private: noncopyable(noncopyable const&); noncopyable& operator=(noncopyable const&); };
class Base: noncopyable
{
public:
Base() {}
virtual ~Base() {}
void init() { some.reset(this->initImpl()); }
private:
virtual SomeType* initImpl() { return new SomeType(); }
std::auto_ptr<SomeType> some;
}; // class Base
// same Derived class, that's the beauty of insulation :)
Isn't it much better ?