tags:

views:

150

answers:

4

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?

+7  A: 

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.

Bojan Resnik
+2  A: 

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.

visitor
I am using boost::shared_ptr
amitlicht
+1 for containers of unique_ptr!
AshleysBrain
+1  A: 

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?).

Space_C0wb0y
+4  A: 

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.

Phil Nash