Avoid non-const references

[I know this is in the Google style guide, consider this another version of the same argument.]

In general, arguments should be values, const references, or pointers, _not_ bare references. Why?

Well, you might write a function inc which increments an int.

  void inc(int& i)
  {
     ++i;
  }

which would then be called in someone's code like this:

    int i = 0;
    foo(i,i+1);
    bar(i);
    inc(i);
    baz(i);

The reader of that code doesn't have any reason to assume that i has any value other than zero, unless they know about the implementation of inc. But, you say, they should be able to read my excellent function names, and understand that “inc” is short for “increment”. But consider the next person to read this code: they have a lot on their mind, a lot to understand, and they're probably looking for a bug, so may be extra suspicious of your lovely code.

So do this: even for this innocuous incrementer, declare it so:

  void inc(int* i)
  {
     ++*i;
  }

and then when the read the code at the call site, a big ugly ampersand tells them someone may have messed with their i:

    int i = 0;
    foo(i,i+1);
    bar(i);
    inc(&i);
    baz(i);

But...

If your function is more complex than inc, and you believe the code is more readable with the reference, just capture the argument locally. And don't be such a baby.

void set_first_element_to_one_if_has_at_least_one_elemet(std::vector<int>* pv)
{
  if (pv->size() == 0) return;
  (*pv)[0] = 1;  // Don't like this?
  auto& v = *pv;
  v[0] = 1; // Look, much nicer
}
non-const-references.txt · Last modified: 2016/06/23 08:51 by awf
CC Attribution 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0