1

Sorry for the confusing title, and sorry if this is a duplicate (I tried searching for an answer online), hopefully this example clears it up:

Basically, would it be better to do this:

void fill(vector<int> & v);

int main() {
  vector<int> v;
  fill(v);
  return 0;
}

or this:

vector<int> fill();

int main() {
  vector<int> v = fill();
  return 0;
}

I've been reading about how in C++11 the compiler will move the return results of functions rather than copying them. Is one of these better than the other? Or is it simply preference?

Dillydill123
  • 693
  • 7
  • 22
  • You just use std::move and you will be fine but better to use reference. – Shiv Jan 04 '17 at 06:24
  • 3
    In the first example, do you really mean `const`? How can `fill()` modify a `const vector&`? – Robᵩ Jan 04 '17 at 06:52
  • Some insightful answers to a very similar question here: http://stackoverflow.com/questions/3134831/in-c-is-it-still-bad-practice-to-return-a-vector-from-a-function – acraig5075 Jan 04 '17 at 06:58
  • Useful discussion: https://blog.knatten.org/2011/08/26/dont-be-afraid-of-returning-by-value-know-the-return-value-optimization/ https://web.archive.org/web/20130930101140/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value – Robᵩ Jan 04 '17 at 06:59
  • sorry about the const, that was a typo! – Dillydill123 Jan 05 '17 at 01:33

2 Answers2

0

From the perspective of Single responsibility principle it is better to use return value for modifying an variable.

For example if you have a fill() function that creates initial configuration for a vector, the function's responsibility is to create initial configurations(read them from db, file or just hard-coded configuration). Not assign the configuration to your variable(that might be also a complex process).

And if you are going to change only 1 variable, it increments the readability of the code. You don't need to remember if the fill() function modifies your variable or not.

cokceken
  • 2,068
  • 11
  • 22
  • you are taking that principal to an extreme, that way operator += also violates it.. – Oleg Bogdanov Jan 04 '17 at 07:35
  • we don't know what fill() does, as i said fill function may be accessing db, file or some other resource to gather information then fill the variable. += only assigns a value to variable, i wouldn't complain about string s = "foo bar"; s += s.substring(1,3); because substring only cares about taking substring of a string. – cokceken Jan 04 '17 at 07:47
-1

The former is better as it avoids a copy operation at the end . But I rather prefer this :

  bool fill(vector<int> & v);

The return flag is used to identify if the function was executed successfully.

seccpur
  • 4,996
  • 2
  • 13
  • 21
  • 1
    With return value optimization, it seems unlikely that `fill()` would have a "copy operation at the end". – Robᵩ Jan 04 '17 at 06:57