How is std::expected useful?

In it’s simplest form, std::expected is a slightly modified std::optional which can return either a normal return value T or an error value E. For example:

std::expected<int, ProcError> ProcessSomething(Data data) noexcept
{
  int ret = calculateStuff(data);
		
  if(ret == -1) 
  {
    return std::unexpected{ProcError::Error1}; 
  }
  return ret;  
}

So how is it useful?

  1. If you use it, you don’t need exceptions. Making a function noexcept has a few benefits.
  • Noexcept functions can be optimized by the compiler, leading to potential performance improvements.
  • They allow you to specify that a function will not throw any exceptions, improving code reliability and predictability. This enables better error handling and simplifies exception safety guarantees.
  • Noexcept functions facilitate the use of move semantics, allowing for efficient and safe resource management in C++ code.

2. In the calling funtion, you can check if what returned was a value or an error, without causing any exceptions:

if (ret.has_value())

3. In the calling function, you can check if what returned was an error, but you can cause an exception if this is the norm in your legacy code or other parts of your code:

//this will throw if an error is returned
int returnValue = ret.value();		

In

Leave a Reply

Your email address will not be published. Required fields are marked *