On 1/14/2016 1:28 AM, Stefan Ram wrote:
>
> Which possibility (regarding the kind of parameter
> declaration) should be preferred [for in-arguments]?
It depends mainly on at least three things:
• Whether you'll store a logical copy of (or maybe a reference to) the
argument.
• The cost of actual copying.
• Whether you're talking about a general default, or a particular case.
In addition it depends marginally on whether you place significance on
possible aliasing problems and/or aliasing optimization opportunities
(like in a copy assignment operator for self-assignment).
It also depends marginally on what value you place on the `const`
mechanism to make code more maintainable and/or more likely correct.
• • •
The general modern default according to many :) is to pass value
in-arguments by value, and make them non-`const` so they can be moved.
When one considers only one level of calling, where in the end the
argument value is logically copied, this is never significantly worse
than passing by reference to `const`, and it avoids one actual copying
for an rvalue actual argument, so in that case it's better.
But when one considers many levels of calling, say N levels, it
introduces O(N) actual copy operations, compared to just 1 for pass by
reference-to-`const`.
Also, the lack of `const` is a problem if one values `const` as a way to
constrain the possible effects of the code (maintainability & correctness).
In short it depends – very much. I think that supporting moving is an
/optimization/, which should take second place to correctness and
maintainability unless measurements show that it's really needed, and I
regard `const` as a significant means to ensure correctness and
maintainability, while I don't regard aliasing problems as significant
(never encountered that!), and so I place more weight on `const` as
correctness than moving as optimization. As a general default.
• • •
The above seems to be what Herb Sutter also argues now, according to a
report about a video of his CppCon 2014 talk, “Back to the Basics!
Essentials of Modern C++ Style”. I haven't seen it, but here's a link (I
haven't tried it): <url:
http://youtu.be/xnqTKD8uD64?t=51m4s>. I got
that and the info that Herb now advocates good old ref-to-`const` as
default, from <url:
http://cpp.indi.frih.net/blog/2014/10/overthinking-a-critique-of-herb-sutters-recommendations-on-function-arguments/>,
which I found while googling references to show that Herb had the
opposite view, which I mistakenly believed had.
Cheers & hth.,
- Alf