On 09/09/2013 09:43 AM, Andrei Alexandrescu wrote:
Great talk indeed!
I am late to the party so instead of commenting on Reddit I will write here.
There are two points made in the talk that favor out parameters over
The Composability Argument
* Appending to containers: cheap
* Concatenating containers: expensive
The Measurements Argument
* Which one is faster?
// API 1: Returns next line (with terminator)
// or empty string at end of file
// API 2: Fills string with next line (with terminator)
// returns false at end of file
bool nextLine(istream&, string& s);
This topic happens to be one of my favorite interview questions. :)
If program correctness is valued, the by-ref out parameter may not be
the faster option because the caller may not want to pass in a precious
container to a function only to be halfway appended to it.
Imagine that the function appends N/2 items to the caller's container
and then throws. If that half-baked state is not desired, either the
function itself or the caller may have to undo what has already been
If the function should not append but first clear the container and
then create it anew, then fair enough, we would be taking advantage of
already-allocated buffer of the container. (A valid consideration for
arrays but not every pointer-based data structure takes advantage of old
buffers.) But still, for correctness, the function should not append but
create anew (on top of the existing buffer), which necessitates
"concatenation" on the caller side anyway.