[OT] My C++ talk at GoingNative 2013
Ali Çehreli
acehreli at yahoo.com
Sat Sep 21 22:32:35 PDT 2013
On 09/09/2013 09:43 AM, Andrei Alexandrescu wrote:
> http://www.reddit.com/r/programming/comments/1m1izv/goingnative_2013_writing_quick_code_in_c_quickly/
>
>
> Andrei
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
return-by-value:
<quote>
Slide 33/40:
The Composability Argument
* Appending to containers: cheap
* Concatenating containers: expensive
Slide 34/40
The Measurements Argument
* Which one is faster?
// API 1: Returns next line (with terminator)
// or empty string at end of file
string nextLine(istream&);
// API 2: Fills string with next line (with terminator)
// returns false at end of file
bool nextLine(istream&, string& s);
</quote>
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
appended.
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.
Ali
More information about the Digitalmars-d-announce
mailing list