views:

357

answers:

3

I've asked a couple questions (here and here) about memory management, and invariably someone suggests that I use boost::shared_ptrs.

Given how useful they seem to be, I'm seriously considering switching over my entire application to use boost::shared_ptrs.

However, before I jump in with both feet and do this, I wanted to ask -- Has anyone had any bad experiences with boost::shared_ptrs? Is there some pitfall to using them that I need to watch out for?

Right now, they seem almost too good to be true - taking care of most of my garbage collection concerns automatically. What's the downside?

A: 

Dynamic memory overhead (i.e., extra allocations) plus all the overhead associated with reference counted smart pointers.

MSN
+2  A: 

Boost shared pointers or any other technique of memory management in C++ is not a panacea. There is no substitution for careful coding. If you dive into using boost::shared_ptr be aware of object ownership and avoid circular references. You are going to need to explicitly break cycles or use boost::weak_ptr where necessary.

Also be careful to always use boost::shared_ptr for an instance from the moment it is allocated. That way you are sure you won't have dangling references. One way you can ensure that is to use factory methods that return your newly created object in a shared_ptr.

typedef boost::shared_ptr<Widget> WidgetPtr;
WidgetPtr myWidget = Widget::Create();
m-sharp
+4  A: 

The downside is they're not free. You especially shouldn't use shared_ptr/shared_array when scoped_ptr/scoped_array (or plain old stack allocation) will do. You'll need to manually break cycles with weak_ptr if you have any. The vector question you link to is one case where I might reach for a shared_ptr, the second question I would not. Not copying is a premature optimization, especially if the string class does it for you already. If the string class is reference counted, it will also be able to implement COW properly, which can't really be done with the shared_ptr<string> approach. Using shared_ptr willy-nilly will also introduce "interface friction" with external libraries/apis.

Logan Capaldo
strings don't usually use COW. It doesn't play nicely with multithreaded apps, so most implementations dropped it again. Which means string copies are somewhat costly.
jalf
GCC's string implementation still uses COW IIRC. But with C++0x they will *likely* be disallowed (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2668.htm) - and good riddance.
Greg Rogers