|
Boost : |
Subject: Re: [boost] expected/result/etc
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2016-02-11 17:57:49
On Wed, Feb 10, 2016 at 9:23 PM, Gavin Lambert <gavinl_at_[hidden]>
wrote:
> On 11/02/2016 15:08, Emil Dotchevski wrote:
>
>> Dereferencing a null shared_ptr is something that easily could happen at
>> runtime. Are you saying that it shouldn't assert in this case? Are you
>> saying that that assert is useless? Are you saying that the correct design
>> is to throw? Or is the correct design to assert and throw?
>>
>
> I answered that in the next paragraph:
>
> On 11/02/2016 14:11, I wrote:
>
>> You could assert *and* throw (or abort, if you don't know how to
>> recover from it), although arguably the assert is less useful if
>> you're repeating the same condition outside the assert anyway. But
>> you can't just slap an assert in and call it a day, at least not for
>> this sort of condition.
>>
>
> Or you could just throw. I'm not convinced that the assert itself adds
> any particular value, aside from possibly being more in-your-face when
> running a debug build. (But thrown exceptions can be equally in your face
> in both debug and release builds if you have a debugger attached, and if
> throwing exceptions is unusual so you haven't disabled "break on exception
> throw".)
It appears that you think that C++ exceptions are "unusual" in the same way
OS exceptions are unusual: the OS detected something bad going on and
raises an exception, as many OSes do for example in the case of
dereferencing a null pointer. That's not at all what C++ exceptions are.
They are in fact specifically designed to replace the need to return error
codes, so that handling errors is simpler, safer and more testable.
As for shared_ptr::operator*, I know it could be made to throw, but that
would be incorrect design. I mentioned shared_ptr to make the point that
you're wrong that this kind of design decision can not be made in generic
C++ code. STL too is full of generic functions that throw to indicate a
failure, and others that do not, without giving the user a choice. Even at
the language level, consider that in C++ constructors don't give you the
option to return an error code, the only way for them to fail is by
throwing. Why? Because that is the correct design.
Emil
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk