Boost logo

Boost :

From: Rani Sharoni (rani_sharoni_at_[hidden])
Date: 2003-12-18 12:06:07


AlisdairM wrote:
> "Rani Sharoni" <rani_sharoni_at_[hidden]> wrote in
> news:brshl7$r8m$1_at_[hidden]:
>
>> Why is it important that the shared_ptr(weak_ptr<Y> const & r)
>> constructor throws an exception?
>> I can't avoid thinking that it can easily affect the exception safety
>> of code that uses it and this exception indicates about a bug in many
>> cases.
>
> IIUC, the issue occurs when resource the weak_ptr refers to no longer
> exists, or at least can no longer be tracked through the weak_ptr.
>
> Given the weak reference has become invalid, what behaviour would you
> prefer when trying to make a shared_ptr out of it?
>
> The exception forces you to consider the possibility, and if no-throw
> guarantees or exception-specifications are a concern you must
> explicitly
> dead with it. Any alternative would seem to involve some sort of
> post- construction test to see if I made a valid shared_ptr. In
> other words, my constructor may fail to give me a valid object. This
> is one of the
> specific problems exceptions exist for, signalling a failure to
> construct. Once you allow objects to construct with invalid states,
> the rest of your code pollutes with state-checks. It is much simpler
> to code with that exception up front, and not worry about such issues
> for the remaining lifetime of your object.

It still bothers me that it's easy to write code like the following:
~A::A()
{
    shared_ptr<T> p(weak_ptr_);
    p->cleanup();
}

My concern is that this pitfall is very easy to fall into.

I prefer something like two global functions:
share_ptr<T> shared_from_weak() throw();
share_ptr<T> shared_from_weak(throw_t); // throw(bad_weak_ptr);

Better names are probably out there.

Thanks,
Rani


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk