I don't really need to share the objects, but i do want to make sure no memory leakage occurs. Is it correct to use shared_ptr in this case?
If you are using boost, boost::ptr_vector might be better suited for your needs.
If not, then you can either use shared_ptr
as you suggested or manually delete the elements of the vector once you are done with them.
From maintenance point of view, shared_ptr
would be the preferred solution. Note, however, that shared_ptr
can bring some performance penalties, which may or may not be significant for your application.
It is a bit of an overkill, but there isn't a much better smart pointer for that. You might also consider boost's pointer containers.
In C++0x you'd be able to store std::unique_ptr
in containers, which is closer to your needs.
You can also use Boost.PointerContainer. Using a shared_ptr
expresses shared ownership. Now if you are sure, that your objects are bound to the lifetime of the container, then a PointerContainer is the better option design-wise (is that even a word?).
If low-level performance/ memory usage are not critical requirements (ie 97% of all cases) then just go with shared_ptr. It's straightforward and well understood.
If you really want to keep things tight and/ or express the ownership intention more precisely then boost::ptr_vector might be better - but if your class doesn't manage any other memory then just manually deleting in your destructor is not as big a sin as we're sometimes led to believe ;-) I'm a big RAII proponent, but still do this from time to time.