开发者

I can't use std::vector of auto_ptr - should i use shared_ptr?

开发者 https://www.devze.com 2022-12-22 19:09 出处:网络
I don\'t really need to share t开发者_JAVA百科he objects, but i do want to make sure no memory leakage occurs.

I don't really need to share t开发者_JAVA百科he 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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号