Boost logo

Boost :

Subject: Re: [boost] std::map::find() wrapper
From: Olaf van der Spek (ml_at_[hidden])
Date: 2011-05-01 09:38:55


On Sat, Apr 30, 2011 at 11:18 PM, Rob Riggs <rob_at_[hidden]> wrote:
> On 04/30/2011 06:55 AM, Olaf van der Spek wrote:
>>
>> exceptions are for exceptional cases
>
> That oft-used bromide lacks any useful information about when the use of
> exceptions is appropriate.
>
> Exceptions should be used (thrown) when contracts are violated or invariants
> cannot be maintained.  The only time they should not be used in these cases
> is when checking the invariants would impact performance to such a degree
> that allowing undefined behavior may be preferable.  And in this case, do
> what map and vector do: provide a checked and unchecked version.
>
> A precondition for at() is that the key exists in the map.  It is perfectly
> legitimate for at() to throw an exception for violating its precondition.

Of course. But I'm looking for a find wrapper. Find doesn't have such
a precondition and the wrapper shouldn't have such a precondition
either.

> And /it is perfectly legitimate to make use of this behavior in one's code/.
>  That is, there is nothing wrong with allowing an exception to be thrown if
> you can afford the stack unwinding.
>
> Two bits of code:
>
> if (foo.good()) {
>    do_something_with(foo);
> }
>
> and
>
> try {
>    do_something_with(foo);
> } catch (not_good&) {}
>
> Both are valid.  And sometimes the latter is most appropriate.
>
> Personally, I tend to be more averse to functions that return bare pointers.
>  Given the choice of a function that returns a bare pointer which may be
> NULL or using at() & try/catch, I would probably choose at() first.

I'd prefer the other way around.

Olaf


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