When I have a class that contains pointers as member variables what type of smart pointer should they have if I want don’t want to use plain pointers? They do not need to be shared (so no shared_ptr necessary). scoped_ptr won’t work since I often need to build the objects outside of the initialization list.
Or is it maybe common practice to use a scoped_ptr during the creation when something can still fail (exceptions thrown etc.) and afterwards assign them to plain pointers?
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 thereset()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:
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.