Or how to improve readability and reduce errors.
void foo(T& out) - How to fix output parameters
by Jonathan Müller
From the article:
There are some cases where you need to return a value from a function but cannot use the return value. It happens, for example, in functions where you want to return multiple values at once. While you can pass multiple inputs to a function - the parameters, you cannot pass multiple return values in the same way.
C++ programmers tend to use a good old (lvalue) reference for that. You take a non-const reference as parameter and assign the output to that reference. The caller will pass a variable and upon function completion find the value of the variable changed.
Yet this approach has some problems: For starters, it is not obvious when just looking at the call that the variable is going to be changed. This is the reason that C++ style guides such as the one used by Google recommend using a pointer for that. The caller then has to explicitly pass in the address of the variable, making it explicit.
But with a pointer you can now pass in nullptr, you have to check for that in the function: A pointer where you really mean “reference” does not follow the guidelines I’ve been advocating for.
So is there not a universal solution?
There is, but first we need to understand the full scope of the problem.
Add a Comment
Comments are closed.