Usage of references as parameters

closed account (ywbpSL3A)
I've been working through "C++ Primer (5th Edition)" and stumbled upon a predicament: how do I know when to use a reference as a parameter?

For example, in the following snippet of code the char parameter c is not a reference - why? Is it due to its minimal size (1 byte)?

1
2
3
4
5
6
7
8
9
10
11
12
13
string::size_type find_char(const string &s, char c, string::size_type &occurs)
{
   auto ret = s.size();
   occurs = 0;

   for (decltype(ret) i = 0; i != s.size(); ++i) {
      if (s[i] == c) {
         if (ret == s.size())
            ret = i;
         ++occurs;
      }
   }
}


And then there's this second code snippet; again, I do not quite grasp as to why the iterators are not references, since, in my opinion, it would be more efficient (the same goes for the int):

 
int sum(vector<int>::iterator, vector<int>::iterator, int);
Last edited on
Have you read: http://www.cplusplus.com/doc/tutorial/functions/
It has some notes about reference parameters.

Elsewhere:
For built-in types, STL iterators, and function object types pass-by-value is usually appropriate.


The char, int, double, raw pointer, etc are really cheap to copy and there is no side-effects in copying them.

The iterators are most likely decorated pointers and therefore copying them is no different from copying raw pointers.
const string &s - passed by reference because a string can be costly to copy.
char c - passed by value because it is small and cheap to copy.
string::size_type &occurs - passed by reference so that it can be modified by the function (it works as an extra return value).
The function is missing return ret; at the end.
closed account (ywbpSL3A)
Thanks for the read, it cleared up most of my troubles.
Topic archived. No new replies allowed.