E
E. Robert Tisdale
Richard said:[restoring over-snipped context]
Avoid functions that modify their arguments.
Pass a const reference and return a result by value.
Would you give the same advice
if the object being modified were a million-element vector?
Yes.
Elaborate a little. An example might help.
You might be surprised
struct I {
int i_;
/* and maybe some other stuff */
}
typedef std::vector<I> Vector;
/* Function which sets element p of a Vector to value q
As recommended, function doesn't modify its arguments
but returns a copy.
*/
Vector afunct (const Vector & v, int p, int q) {
Vector temp(v);
temp[p].i_ = q;
return temp;
}
int main(int argc, char* argv[]) {
Vector v(1000000);
for (int i = 0; i < 1000000; ++i) {
v = afunct(v, i, i);
}
/*...*/
return 0;
[snip]}
Still think it's a good idea?
The problem with your example is that
you have not justified modifying std::vector<I> v *in-place*.
You contrived a ridiculous *straw-man* function afunct
Ridiculous, certainly.
But it's not a strawman, it's a counter-example.
It's a function which precisely complies
with your "recommendation" and illustrates its absurdity:
... which I notice you conveniently snipped from your reply.
It was redundant given the quote that you snipped:
"Avoid defining functions that modify their arguments
because they compel programmers to declare an pass variables
which may otherwise be constants in the rest of the program.
Reserve functions that modify their arguments
to situations where an object *must* be modified in-place."
If I am missing your point, please elaborate.
You might want to check on the definition of "strawman"
before you use it again.
http://www.don-lindsay-archive.org/skeptic/arguments.html#straw
Of course I "noticed". That's precisely my point.
Why, then, couldn't you avoid the assignment statement?
You never told us that.