Boost logo

Boost :

From: Edward Diener (eddielee_at_[hidden])
Date: 2003-12-18 16:35:06

Rani Sharoni wrote:
> Peter Dimov wrote:
>> Rani Sharoni wrote:
>>> Why is it important that the shared_ptr(weak_ptr<Y> const & r)
>>> constructor throws an exception?
>> If a function's requirements are met, but the postcondition cannot,
>> this function should throw an exception.
>> It is not possible to place a !r.expired() requirement on the
>> constructor, because the user can never enforce it reliably. The only
>> remaining
>> shared_ptr in r's ownership group may be destroyed (by another
>> thread, for example) between the r.expired() test and the constructor
>> call.
>> If you don't want an exception, use r.lock().
> It seems that the lock construct is superior because it encourage the
> user
> to condition the dereferencing. OTOH the throwing constructor is easy
> to use and therefore users might mistakenly abuse it. I know that it
> can be avoided after realizing what the purpose of weak_ptr is but
> maybe replacing this constructor with throwing well-named free
> function will help to avoid potential pitfalls.

I don't agree. I don't see what the purpose is to replace a throwing
constructor with a throwing free function. In either case the user will need
to catch the exception to handle the case where the weak_ptr doesn't point
to anything. One shouldn't protect abuse by making a logical design less
elegant merely to make end-users feel somehow safer when they are not. Since
one of the ideas of a shared_ptr is that it can be created from a weak_ptr,
why take this out of the shared_ptr design. I think we are far enough along
in modern C++ programming to know that constrcutors can throw exceptions if
the value(s) passed into the constrctor are unexpected at run-time.

Boost list run by bdawes at, gregod at, cpdaniel at, john at