To be honest, I wasn't surprised. I was not expecting the exact same code but I was expecting something similar, for various reasons:
has_value() is just about returning a bool. No reason to cost more than a simple access to member variable.
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:
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 ;)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
To be honest, I wasn't surprised. I was not expecting the exact same code but I was expecting something similar, for various reasons:
has_value()
is just about returning abool
. No reason to cost more than a simple access to member variable.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:
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 ;)