does `const auto` have any meaning?

C++C++11Constants

C++ Problem Overview


I think the question is clear enough. Will the auto keyword auto-detect const-ness, or always return a non-const type, even if there are eg. two versions of a function (one that returns const and the other that doesn't).

Just for the record, I do use const auto end = some_container.end() before my for-loops, but I don't know if this is necessary or even different from normal auto.

C++ Solutions


Solution 1 - C++

const auto x = expr;

differs from

auto x = expr;

as

const X x = expr;

differs from

X x = expr;

So use const auto and const auto& a lot, just like you would if you didn't have auto.

Overload resolution is not affected by return type: const or no const on the lvalue x does not affect what functions are called in expr.

Solution 2 - C++

Maybe you are confusing const_iterator and const iterator. The first one iterates over const elements, the second one cannot iterate at all because you cannot use operators ++ and -- on it.

Note that you very seldom iterate from the container.end(). Usually you will use:

const auto end = container.end();
for (auto i = container.begin(); i != end; ++i) { ... }

Solution 3 - C++

Consider you have two templates:

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

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

Solution 4 - C++

Compiler deduces the type for the auto qualifier. If a deduced type is some_type, const auto will be converted to const some_type. However, a good compiler will examine the whole scope of auto variable and find if the value of it changes anywhere. If not, compiler itself will deduce type like this: auto -> const some_type. I've tried this in Visual studio express 2012 and machine code produced is the same in both cases, I'm not sure that each and every compiler will do that. But, it is a good practice to use const auto for three reasons:

  • Preventing coding errors. You intended for this variable not to change but somehow somewhere in its scope, it is changed.
  • Code readability is improved.
  • You help the compiler if for some reason it doesn't deduce const for auto.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrubenvbView Question on Stackoverflow
Solution 1 - C++antonakosView Answer on Stackoverflow
Solution 2 - C++BenoitView Answer on Stackoverflow
Solution 3 - C++Kirill V. LyadvinskyView Answer on Stackoverflow
Solution 4 - C++BJovkeView Answer on Stackoverflow