Type inference lets the compiler determine a variable’s type from its initializer or context. In modern C++, auto reduces verbose declarations, especially with iterators and templates, but it does not remove the need to understand the resulting type. section 3.2 section 2.0
Use type inference carefully:
- Prefer auto when the exact type is obvious or cumbersome, such as an STL iterator. section 3.2 section 6.8
- Specify references when copying a larger object would waste work: auto& aliases the object, while auto makes a copy. section 3.2
- Check deduced signedness and ownership before using auto in loop controls or element variables. section 3.2
The unsigned countdown trap
A reverse loop such as `for (auto i = values.size() - 1; i >= 0; --i)` can run past the container boundary because size() deduces an unsigned type. Use an explicitly signed `int` when that is the intended loop control type. For larger elements, likewise prefer `auto&` in range-based loops to avoid copies. section 3.2
Listing 3.4 Using auto to let the compiler deduce correct types
int main() {
std::vector<int> values;
for (auto i = 0; i < 10; ++i) #1
values.push_back(i*2);
int key = 4;
if (auto it = std::find(values.begin(),
values.end(), key); it != values.end()) #2
std::cout << key << " was found\n";
else
std::cout << key << " was not found\n";
return 0;
}
Compare explicit declarations with auto for an index and an iterator; the compiler supplies the iterator type while the code remains readable. section 3.2
Listing 3.5 A subtle misuse of auto
int main() {
std::vector<int> values;
for (int i = 0; i < 10; ++i)
values.push_back(i*2);
for (auto i = values.size() - 1; i >= 0; --i) #1
std::cout << values[i] << '\n';
return 0;
}
Inspect the compact reverse-loop example that exposes auto’s unsigned-type hazard. section 3.2















