Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
non-const-references [2015/01/07 21:03] – created awfnon-const-references [2016/06/23 08:51] (current) awf
Line 1: Line 1:
-==== Avoid non-const references ====+===== Avoid non-const references =====
  
-In general, arguments should be values, const references, or pointers, /not/ bare references.  Why?  +[I know this is in the [[https://google.github.io/styleguide/cppguide.html#Reference_Arguments|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. Well, you might write a function ''inc'' which increments an int.
Line 42: Line 44:
 </code> </code>
  
 +==== 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.
 +<code>
 +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
 +}
 +</code>
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