If you're just wanting to store member pointers in a smart pointer type class so you can't/won't forget to delete them, then a standard choice would be auto_ptr
. It's in the STL and is easily "reset" with the reset()
function when you need to release the current memory allocated to it and replace it with a new object.
You will still want to implement your own copy constructor and assignment operators for the classes which have auto_ptr members. This is due to the fact that auto_ptrs assignment operator transfers ownership of the underlying object so a default assignment operator will not have the effect you want.
Here is what the class might look like:
class X
{
public:
X() :p(new ClassToManage) {}
X(const X ©)
:p(new ClassToManage(*copy.p))
{
}
X &operator=(const X &rhs)
{
this->p.reset(new ClassToManage(*rhs.p));
}
private:
std::auto_ptr<ClassToManage> p;
};
For all other cases I would suggest boost::shared_ptr
. Shared_ptr does do reference counting but you can store them in standard containers which makes them quite useful.
You should ultimately try to rid yourself of using plain pointers for anything which points at allocated memory it's responsible for deleting. If you want to use a plain pointer for accessing or iterating over a plain ole array etc., then that's fine (but ask yourself why you're not using a std::vector), but when you use them to point at something that it is responsible for freeing then you're asking for trouble. My goal when writing code is to have no explicit deletes.