Does `const auto` make sense?

I think this question is clear enough. Whether the auto constant will automatically determine the constant or always return a non-constant type, even if there is, for example. two versions of the function (one that returns const , and the other does not).

For the record only, I use const auto end = some_container.end() before my loops, but I don't know if this is required or even different than regular auto .

+51
c ++ c ++ 11 const
Feb 21 '11 at 19:48
source share
4 answers

You may be confusing const_iterator and const iterator . The first one iterates over const elements, the second one cannot be continued, because you cannot use operators ++ and - on it.

Note that you rarely repeat with container.end() . Usually you will use:

 const auto end = container.end(); for (auto i = container.begin(); i != end; ++i) { ... } 
+19
Feb 21 '11 at 19:57
source share
 const auto x = expr; 

differs from

 auto x = expr; 

but

 const X x = expr; 

differs from

 X x = expr; 

So use const auto and const auto& lot like you would if you hadn't auto .

Return permission does not depend on the type of return: const or no const on lvalue x does not affect which functions are called in expr .

+63
Feb 22 '11 at 3:16
source share

You have two templates:

 template<class U> void f1( U& u ); // 1 template<class U> void f2( const U& u ); // 2 

auto will output the type, and the variable will have the same type as the parameter u (as in the case // 1 ), const auto will make the variable the same type as the parameter u in the case // 2 . So, const auto just pin the const qualifier.

+7
Feb 21 '11 at 19:58
source share

The compiler displays the type of automatic classifier. If the output type is some_type , const auto will be converted to const some_type . However, a good compiler will examine the entire scope of the auto variable and find whether its value changes anywhere. If not, the compiler itself will output this type: autoconst some_type . I tried this in Visual Studio Express 2012, and the machine code is the same in both cases, I'm not sure that every compiler will do this. But it is recommended to use const auto for three reasons:

  • Prevention of coding errors. You intended not to change this variable, but somehow somewhere in it the area has been changed.
  • Improved readability of the code.
  • You help the compiler if for some reason it does not output const for auto .
0
Dec 30 '16 at 9:45
source share



All Articles