Re: Rewriting clone() to return a boost::shared_ptr ?
David Abrahams wrote:
"helix" <andrew.j.line@gmail.com> writes:
As for auto_ptr, I generally stay well away as I can't store them in
STL containers.
But you can convert them to shared_ptr. When you're just transferring
ownership (but not across DLL boundaries) and you don't necessarily
know what the receiver wants to do with the pointer, auto_ptr is
usually a better choice. It's cheaper and it lets you interact with
code that might expect to take ownership of a raw pointer. Once you
give ownership to a shared_ptr, you can never get it back.
IMHO this single fact renders it impractical in the real world -
especially when you have boost's superior smart pointers available
to you. I have to confess that I rarely use raw pointers any more,
relying almost entirely on boost's smart pointers.
Boost's smart pointers are indeed great, but (for the most part) it's
not a matter of being superior to auto_ptr: they have different
purposes and characteristics. The Boost smart pointer designs
explicitly acknowledge the role of auto_ptr by including converting
constructors.
To expand on that a little:
When the factory/clone function has a contractual obligation to create
the new object using 'new X', you should generally return an
auto_ptr<X> since it encodes this contract as part of its type. The
caller can now decide what to do with it as it is known that the
returned pointer can (needs to) be deleted at the end of the object
lifetime.
When the factory/clone function is free to choose the allocation and
disposal mechanisms, the proper return value is shared_ptr<X>, since it
takes care of the disposal without the caller needing to know anything
about it.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]