DEV Community

Discussion on: std::optional from C++17 vs custom type for optional value

Collapse
 
pgradot profile image
Pierre Gradot • Edited

To be honest, I wasn't surprised. I was not expecting the exact same code but I was expecting something similar, for various reasons:

  1. has_value() is just about returning a bool. No reason to cost more than a simple access to member variable.
  2. value() is just a test to decide to return the value or throw an exception. Nothing fancy here.

We may expect the exception to cost a more than a simple access to a member variable. So why ?

This leads me to reason 3. Over the years (and hours spent in Compiler Explorer, you definitively must use it!), I have learned something important: modern compilers are amazing at optimizing code. Way much better that you and me.

And here, take a better look at the code: it tests if the std::optional has a value and get the value conditionally. The compiler then know the exception cannot be thrown and optimizes that out.

Change the code and get a completely different result:

int getStdOptional(const StdOptionalInt& o) {
    return o.value();
}
Enter fullscreen mode Exit fullscreen mode

This generates all the code to handle the exception and it's a lot a code.

I something take a look at the source of standard features. I simply to a CTRL+click in my IDE. std::optional seems crazy but it does much more than my custom type. It is made by and for the standard library developers. And this leads me to reason 4 : these developers are way better than you and me to create powerful, flexible, easy-to-use, robust code ;)