Chapter 2. auto
In concept, auto
is as simple as simple can be, but itâs more subtle than it looks. Using it saves typing, sure, but it also prevents correctness and performance issues that can bedevil manual type declarations. Furthermore, some of auto
âs type deduction results, while dutifully conforming to the prescribed algorithm, are, from the perspective of a programmer, just wrong. When thatâs the case, itâs important to know how to guide auto
to the right answer, because falling back on manual type declarations is an alternative thatâs often best avoided.
This brief chapter covers all of auto
âs ins and outs.
Item 5:âPrefer auto
to explicit type declarations.
Ah, the simple joy of
int x;
Wait. Damn. I forgot to initialize x
, so its value is indeterminate. Maybe. It might actually be initialized to zero. Depends on the context. Sigh.
Never mind. Letâs move on to the simple joy of declaring a local variable to be initialized by dereferencing an iterator:
template<typename It> // algorithm to dwim ("do what I mean") void dwim(It b, It e) // for all elements in range from { // b to e for (; b != e; ++b) { typename std::iterator_traits<It>::value_type currValue = *b; ⦠} }
Ugh. âtypename
std::iterator_traits<It>::value_type
â to express the type of the value pointed to by an iterator? Really? I must have blocked out the memory of how much fun that is. Damn. Waitâdidnât I already say that?
Okay, simple joy (take three): the delight of declaring a local ...
Get Effective Modern C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.