Boost logo

Boost :

Subject: Re: [boost] expected/result/etc
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2016-02-11 18:20:03


On Wed, Feb 10, 2016 at 11:19 PM, Michael Marcin <mike.marcin_at_[hidden]>
wrote:

> On 2/9/2016 3:16 AM, Niall Douglas wrote:
>
>>
>> Something missing from the discussion so far is that
>> expected/result/outcome MUST throw exceptions! If you try to fetch a
>> value from a result and it contains an error, there is no alternative
>> to throwing an exception. This fact is why I don't worry about static
>> function initialisers and just go ahead and use
>> error-code-via-system_error throwing constructors, ultimately you
>> need try...catch in there one way or another.
>>
>>
> There most certainly is an alternative!
> I certainly don't want this behavior.
>
> There's no way that accessing the value of a result<T> without checking
> for an error is not a programming error.
> It should be a precondition that to access the value it needs to not
> contain an error.
> It should *not* be throwing an exception because you cannot fail to
> satisfy the postcondition until you meet the preconditions.
>
> Undefined-behavior is the appropriate specification for accessing a value
> from a result that contains an error.

It depends what's your goal. If you want to avoid logic errors in error
handling code (as you should), then you don't want accessing the result
without checking for error to be undefined behavior.

Consider the following C code:

int * p=(int *)malloc(sizeof(int));
*p=42;

Of course the correct code is:

int * p=(int *)malloc(sizeof(int));
if( !p )
  return error;
*p=42;

Niall's motivation is to make code like this safer without resorting to
exceptions. But the best way such code is made safe is by using exceptions.
In C++ you can write:

int * p=new int;
*p=42;

without invoking undefined behavior, because the compiler will
automatically generate code that effectively does:

int * p=new int;
if( !p )
  return error;
*p=42;

Emil


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