by Karellen · 4y ago · 0 comments
If a function returns a value, have it return that value, instead of using an out-parameter. Passing in-parameters by const reference rather than by value is a nice win because the semantics of the function remain clear. Input parameters still look like input parameters, you're just preventing unnecessary copies where it's easy to do so. Returning a value as an out-parameter rather than just returning it is a performance hack that prevents a copy, but at the expense of muddying the semantics of the function.
As the prophet says: we should forget about small efficiencies, say about 97% of the time. Write code that clearly expresses what it does. Return your return values. If you run a profiler over your code and you notice that some returns are causing a performance problem - sure, at that point, add an overload that takes an out-parameter and use it at the frequenty-executed hot spot.
SomeType result;
if (!do_something(&result))
return;
process(result);
with this: std::tuple<bool, SomeType> ret = do_something();
if (!std::get<0>(ret))
return;
process(std::get<1>(ret));
You could improve it a bit by using `auto` or returning a struct with named members, but quite often I still find it less readable. Especially in situations that are more complex than this example, where e.g. you fallback to another function to fetch `result` if `do_something` failed. const std::optional<SomeType> result = do_something();
if (!result.has_value()) {
return;
}
process(result.value());
This is nicer than the output parameter in my opinion, because it may be unclear what the meaning of a default constructed SomeType is. Default values are sometimes dangerous if the default is a real, valid input - errors and invalid states can end up being passed through.C++ doesn't have great support for sum types, so this is all always going to be pretty non-ergonomic, and the compiler doesn't always warn if you forget to do things. I might even say that the main advantage of using sum types is gone in C++ - you actually can forget to check has_value and call operator* on an empty optional.
It would be so easy for someone to make a mistake and write:
process(*do_something());
And invoke undefined behaviour. Whereas processing a default-constructed SomeType is at least not undefined behaviour (depending on what SomeType is, and what process does...).This whole thing is a mess, I hate C++, thinking about UB all the time...
do_something().and_then(process);
Or structured bindings: auto [error_code, result] = do_something();
if(error_code == 0) {
process(result);
} auto [error, value] = do_something()
if(!error)
process(value)
Is there something wrong with this?However, if you are compiling at -O0 without any optimizations this may not happen.
There are probably exceptions and loopholes just like with literally everything in C++, but there's this line:
> Return value optimization is mandatory and no longer considered as copy elision; see above.