auto and auto& and const

Viewed 271
auto x1 = exp1;
auto& x2 = exp2;

Do I understand correctly that variables declared with auto (x1) will never be const, even if exp1 is const (for ex. a function that returns const). When with auto&(x2) will be const if exp2 will be const. Even if auto is a pointer.

auto it = find(cont.cbegin(), cont.cend(), value);

Here despite I use cbegin and cend it will be non-const iterator, and to be const_iterator I should write

const auto it1 = find(cont.cbegin(), cont.cend(), value);
1 Answers

Do I understand correctly that variables declared with auto (x1) will never be const

Correct.

When with auto&(x2) will be const if exp2 will be const.

A reference is never const; references cannot be cv qualified. x2 could be a reference to const.

auto it = find(cont.cbegin(), cont.cend(), value);

Here despite I use cbegin and cend it will be non-const iterator

it would be a non-const qualified object of const_iterator type.

const auto it1 = find(cont.cbegin(), cont.cend(), value);

it1 would be a const qualified object of const_iterator type.

Indirecting through a const_iterator (typically) gives you a reference to const, and thus you cannot modify the pointed object.

A const object cannot (generally) be modified. Thus, you for example cannot increment a const qualified iterator.

Related