I'm porting code to C++17, trying to use the new features while possible. One thing I like is the idea to use std::optional
to return or not a value in a function that may fail in some conditions.
I was curious about the possible usages of this new feature, and I'm thinking in start to use it to replace optional arguments in functions, so:
void compute_something(int a, int b, const Object& c = Object(whatever)) {
// ...
}
Becomes:
void compute_something(int a, int b, std::optional<Object> c) {
auto tmp = c.value_or(Object(whatever));
// ...
}
According to the official doc:
If an optional contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though the operator*() and operator->() are defined.
So, every time we use a std::optional to pass arguments, it implies a creation of copies than can be a penalty performance if the object is big.
I love the idea, because it make the code simpler and easy to understand but, is there any advantage?