Boost logo

Boost Users :

From: Noah Roberts (roberts.noah_at_[hidden])
Date: 2008-05-16 13:43:58


Kevin Martin wrote:
>> 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)

As was mentioned by another, func1 seems to be poorly designed in that
it is taking the wrong type of argument. 'x' should most certainly be a
reference, not a pointer. This does not guarantee that nobody will do
something as silly as taking the address of that object and keeping a
pointer around, but it does advertise that it definitely should not be.

If it does you can execute the developer that did it.

Having fixed that, your call looks like this:

func1(*func2());

Or the more sure:

boost::shared_ptr<int> p = func2();
func1(*p);

Now you're not assuming that p is not a temporary!


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