C++ Temporary References – Pros and Cons

arrayccoding-standardscoding-stylereference

In C and C++ (and I guess other languages that allow taking a "reference" to an array element or something similar), when you have an array like type, accessing individual elements of such an array can be done "directly" or via a temporary reference or pointer.

Example:

// Like this:
for(int i=0; i<n; ++i) {
   theArray[i].frobnicate();
   theArray[i].shrub();
   if(i % 2) {
      theArray[i].modulize();
   }
}

// Or like this:
for(int i=0; i<n; ++i) {
   TheType& elem = theArray[i];
   elem.frobnicate();
   elem.shrub();
   if(i % 2) {
      elem.modulize();
   }
}

Obviously if the loop body becomes too complex some refactoring should be used and the whole access moved to a separate function/method that would naturally operate on a single element of the array, but for cases where there are few acesses that are only used in one loop, it may be more convenient to keep them directly in the loop.

We have been debating which form we should prefer in our team and opinions are mixed, therefore I'm interested in whether there exist some guidelines, especially wrt. C++.

Edit: This is purely about style if you will. Performance is irrelevant, as our C++ compiler actually should generate exactly the same code in both versions.

Best Answer

Each approach has advantages.

The temporary reference approach has the advantage that you get to name the reference. This can provide additional information to help make the code more self-explanatory. It also eliminates having multiple instances of the same expression to access the variable.

The no-reference approach is one-line shorter. And if you only access the member once or twice, the benefit of eliminating multiple instances is much less.

I've written coding practices documents. If you feel you must have a policy on this, I would suggest noting the advantages of each and recommending the no-reference approach where the code is simple and the reference approach where either the expression would be repeated many times or having the reference named adds to code readability.

You don't have to have a rule for everything, especially where there's no clear major advantage of either approach and no specific problem you're trying to avoid.

Related Topic