Re: auto_ptr vs. boost shared_ptr
Vinzenz Feenstra wrote:
I've just read the boost documentation on shared_ptr
(http://www.boost.org/libs/smart_ptr/shared_ptr.htm) and it
was not clear to me what advantage using shared_ptr over
std::auto_ptr would be.
If you'd like to compare std::auto_ptr<> with a boost smart
pointer, it would be comparable to the boost::scope_ptr.
Not really. All three have different semantics.
The adavantage of boost::shared_ptr is that you can share the
objekt inside of the shared_ptr with many classes and the
Objekt will be freed if the last copy of the shared_ptr objekt
with your pointer in it is destroyed.
Which is only an advantage if those are the required semantics.
If you manage your pointer with a std::auto_ptr<> the pointer
will be available only in one sole instance of an auto_ptr<>,
so you cannot share the same managed pointer with others.
Which is generally why I use it.
A good example is when passing a pointer to another thread. You
certainly don't want to access it further in the first thread
(because the other thread is now owner). std::auto_ptr is ideal
for this. It's also indicated for returning objects from
factory functions: the caller can release the pointer (which
for obvious reasons cannot be supported with shared_ptr), and
use whatever management strategy he wishes.
Boost::scoped_ptr is nice for things like the pimpl idiom, where
you don't want to share. (And if you forget to inhibit copy, or
to provide one which does the right thing, an accidental copy
won't compile with boost::scoped_ptr, where as with either
shared_ptr or auto_ptr, it will, but the results will have the
In practice, I've found relatively little use for shared_ptr,
although I use auto_ptr rather regularly, and occasionally
scoped_ptr. If I weren't using the Boehm collector, of course,
shared_ptr is often used as a surrogate for garbage collection,
although some care is required when doing so. And I do use
shared_ptr with custom "destructor" objects, which, for example,
free a mutex, rather than destructing the object.
James Kanze email@example.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]