Boost logo

Boost Users :

From: Kevin Martin (kev82_at_[hidden])
Date: 2008-05-16 13:34:45


> I was recently torn between doing this or thinking whether I'm doing
> it
> wrong. I'm still not sure whether using shared pointers everywhere
> with
> null deleters for stack allocated objects is The Right Thing.

I think it depends how much you are relying on the smart pointer.

If you are certain about the scope of the pointer - i.e. you know
where the delete is going to happen and you are using the smart_ptr
purely to guarantee delete is called properly then using a null
deleter and stack based objects is fine. However, if you are using the
smart_ptr to let objects run loose and clear up after themselves, then
this absolutely shouldn't be used.

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. 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());

And to make matters worse, people might be tempted to do this!

func1(func2().get());

By having func1 take a boost::shared_ptr<int> as argument, we can do
this, but we can no longer pass stack objects (unless we can put a
stack object in a shared_ptr)

> It kind of
> defeats the purpose of shared_ptr which is to ensure that the lifetime
> of the pointer is guaranteed for you.

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. 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. If you are having to think about
this anyway, then you will know the lifetime of your pointer and
whether you should pass it or not.

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.

Thanks,
Kevin Martin


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