boost eqiv of std::auto_ptr

C

Christopher

If I have a factory that is allocating objects and returning them from
one of its methods, what kind of smart pointer should I be using?

I would normally use an std::auto_ptr, but was told that it is not as
"safe" as a boost pointer. So, I looked at boost and thought a scoped
pointer was a good fit, but it cannot be copied. My factory has a
number of these things that it allocates and stored in a vector until
the are retrieved.

So, should I be using a boost shared_ptr then? Even though only one
class will be dealing with the allocated object at a time?
 
J

James Kanze

If I have a factory that is allocating objects and returning
them from one of its methods, what kind of smart pointer
should I be using?

It depends on the objects, but either a raw pointer or
std::auto_ptr would seem most appropriate.
I would normally use an std::auto_ptr, but was told that it is
not as "safe" as a boost pointer.

It's safer than boost::shared_ptr, at any rate. There may be
special cases where a factory should return a boost::shared_ptr,
but they are very, very exceptional.
So, I looked at boost and thought a scoped pointer was a good
fit, but it cannot be copied. My factory has a number of these
things that it allocates and stored in a vector until the are
retrieved.

I'm not too sure how that works, but note that you cannot have
an std::auto_ptr in a vector (or any other standard container).
If the objects *are* actually in a vector, you probably can't
(and don't want) to use a smart pointer for them at all---the
vector manages their lifetime.
So, should I be using a boost shared_ptr then? Even though
only one class will be dealing with the allocated object at a
time?

As a basic rule, a factory should not return a
boost::shared_ptr, because this constrains the client code too
much. If boost::shared_ptr is appropriate in the client code,
it has a constructor from std::auto_ptr for this case; if it's
not, however. Once a boost::shared_ptr has gotten control of an
object, it can't let go---there's no way of changing the
ownership policy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top