5/07/2013

Rule for using c++ 0x auto?

'auto' is one of popular keywords in c++ 0x. Now, one of envy lists, which we feel when we see c# or such as script languages, can be reduced. The most typical example of using is when declare 'iterator' in STL.
//when declared typical iter
for (map&ltstring, int>::const_iterator iter = MapScores.begin(); iter != MapScores.end(); ++iter)
{
    cout << "Name = " << iter->first << ", Score = " << iter->second << endl;
}
 
//when used auto
for (auto iter = MapScores.begin(); iter != MapScores.end(); ++iter)
{
    cout << "Name = " << iter->first << ", Score = " << iter->second << endl;
}
(In first one, instead of 'const_iterator', using of cbegin(), cend() is also fine for const appliance. cbegin(), cend() are also added containers of c++ 0x.)

The problem is that lots of c++ developers are already used for one rule, which type of variables always have to be declared. Therefore, inordinate using of 'auto' might bring about confusing and annoying. Furthermore, because of operation through misunderstanding, proportion of debugging time may be longer.

So, I make a rule for me.

  1. when immediately know 'return type' like above code and such as 'for', 'while' loop, when use local variable which available in short scope only.
  2. As much as possible, use 'const auto'. So that, if possible, it uses for 'read only'. I think it can aid to protect wrong operation by means of misunderstanding.

Below link is a stackoverflow thread which discussed for 'guideline using auto'.

http://stackoverflow.com/questions/6434971/how-much-is-too-much-with-c0x-auto-keyword
Personally, I believe that the use of at least is better way.

No comments:

Post a Comment