editor << letters;

editor << letters;

By Aaron Ridout

Overload, 8(37):, May 2000


I have had two replies to my 'Mutable' letter from Overload-34.

mutable - Defensive coding idea from Roger Woollett

A possible solution is to use an object of class type to control the for loop.

class index {
  index(int i){value= i;}
  operator int(){return value;}
  index operator++()
       {return ++value;}
  int value;

You can now write:

for(index i=0; i<10; ++i) fn(i);

This will work if fn takes an int but not if it takes int& .

Roger Woollett

mutable - Defensive coding from Andy Robb

Here are a couple of alternatives for you:

for(int i=0; i<10; ++i)

The inline construction of int(i) returns a ( int const & ) which would catch the coder's change.


for(int i=0; i<10; ++i){
  int const  & ci = i;

This has the advantage that the reference does not change and can be optimised out of the loop.

Andy Robb

mutable Aaron Ridout

Many thanks to Andy and Roger for replying. Andy's solutions are great for the original problem if I were re-visiting the code for low impact (cost / risk) maintenance.

However, if I were writing some green field code, I'd prefer Roger's idea as it is a more object oriented solution, but I have yet to test its impact on speed. It would also have to be converted into a template in order to work with any type, STL iterators for example as well as POD types such as int .

Furthermore, this should work with the for_each template and this new template object should provide a wrapper for the requirements of a set to be iterated over and the function to be called via for_each , then one could write:

void fn( const int &i ) ;


std::list<int> i ;

Perhaps fn should be a member of Iterate, then it could read the index for itself rather than having to be passed in as a formal parameter...

Aaron Ridout

Your Privacy

By clicking "Accept Non-Essential Cookies" you agree ACCU can store non-essential cookies on your device and disclose information in accordance with our Privacy Policy and Cookie Policy.

Current Setting: Non-Essential Cookies REJECTED

By clicking "Include Third Party Content" you agree ACCU can forward your IP address to third-party sites (such as YouTube) to enhance the information presented on this site, and that third-party sites may store cookies on your device.

Current Setting: Third Party Content EXCLUDED

Settings can be changed at any time from the Cookie Policy page.