Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does `const auto` have any meaning?

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.

like image 476
rubenvb Avatar asked Feb 21 '11 19:02

rubenvb


2 Answers

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.

like image 74
antonakos Avatar answered Nov 06 '22 09:11

antonakos


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) { ... }
like image 37
Benoit Avatar answered Nov 06 '22 10:11

Benoit