When I have a class that contains pointers as member va开发者_Python百科riables 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 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.
You could use std::auto_ptr
, which was available prior to TR1 and therefore your code is not dependant on a compiler supporting TR1-smartpointers.
Normally I use a deep_copy_ptr. Right now I know of loki smart_ptr and axter smart pointer that do this. It allow the pointer class to be automatically copied somewhat like if it was a normal member variable (you don't need to define a special assignment operator/copy constructor).
I think you don't have to specifically initialize it in the initializer list (but like a normal pointer, don't use it if it do not have a valid value, obviously).
精彩评论