Boost logo

Boost Users :

From: Nevin \ (nevin_at_[hidden])
Date: 2008-05-16 15:37:17


2008/5/16 Kevin Martin <kev82_at_[hidden]>:
> My problem is module interfaces. I have a module (set of classes) that
> solve a problem, and they require data. They don't care whether that
> data is on the heap, the stack, or the moon. They just want a pointer
> to it. In this case it is arguable that the pointers passed shouldn't
> be smart pointers at all, just normal pointers.

My general rule of thumb is that if mucking with ownership or
lifetime, pass a smart pointer. If not, pass a raw pointer.

> That is fine, but has
> two drawbacks:
>
> a) You have to call get() for all shared_ptr<>s everywhere instead of
> just passing the pointer
> b) You can't do this:
>
> void func1(int *x);
> boost::shared_ptr<int> func2();
>
> func1(func2());

One could always add the following overload:

    inline void func1(shared_ptr<int> const& x) { func1(x.get()); }

> And to make matters worse, people might be tempted to do this!
>
> func1(func2().get());

What is wrong with that?

> Just because the shared_ptr guarantees the lifetime of the pointer,
> doesn't mean you can forget about who has a copy of the pointer and
> why.

They are separate issues. There are times I need to know who has
references to my object, other times it is sufficient to know how many
outstanding references there are, and still other times where all I
need to know is whether or not there are any outstanding references to
my object.

> If you are passing any kind of pointer/reference anywhere, then
> the callee should have a strict, well documented description of what
> it plans to do with that pointer, otherwise anyone may be modifying
> your object without you realizing.

Modifying your object is an orthogonal issue, better handled with
judicious use of const.

> I think using smart pointer without knowing both when and why it is
> being copied is inviting disaster, therefore I don't see the problem,
> but maybe someone can show me an example where this information can't/
> shouldn't be known.

If you get a job at my company, I can show you a couple of examples. :-)

Take your func2. It has no idea who will call it, so it can't
possibly know why (or even if) its return value is being copied. Yet
that is normal, not disasterous for things like factory functions.

Another example: suppose I have a pool of expensive to construct
cookies. My factory function returns them to some caller, and when
the reference count goes to 0, I put the cookie back into the free
pool. I don't know or care how many times the caller copies it; I
just need to know when there are no outstanding references to it so
that I can reuse it.

Regards,

-- 
 Nevin ":-)" Liber <mailto:nevin_at_[hidden]> (847) 691-1404

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net