General features: Auto specifier


Usage / Usability

  • Type deduction happens at compile time
  • Auto ignores references and const/volatile

Hard to write


Hard to know


  • No more uninitialized variables, no more hidden bugs

  • avoid problems related to “type shortcuts”

std::vector<int>::size_type is specified to be an unsigned integral type.
On 32-bit Windows, for example, both unsigned and std::vector<int>::size_type are the same size, but on 64-bit Windows, unsigned is 32 bits, while std::vector<int>::size_type is 64 bits.


the key part of a std::unordered_map is const, so the type of std::pair in the hash table isn’t std::pair<std::string, int>, it’s std::pair<const std::string, int>. But that’s not the type declared for the variable p in the loop above.
As a result, compilers will strive to find a way to convert
std::pair<const std::string, int> objects (i.e., what’s in the hash table) to
std::pair<std::string, int> objects (the declared type for p).
They’ll succeed by creating a temporary object of the type that p wants to bind to by copying each object in m, then binding the reference p to that temporary object. At the end of each loop iteration, the temporary object will be destroyed.


  • The code becomes harder to read due to the abuse of auto variables


Auto does not deduce CV-qualifiers unless declared as a reference

When the initializer for an auto-declared variable is enclosed in braces, the deduced type is a std::initializer_list

Compilation error in case a type can’t be deduced (due to different types)


Quiz – What will happen when calling the following lines?


1.Temporary objects
2.Writable (non-const) entries within the map
3.Const temporary objects
4.Const entries within the map

You may also like...

Leave a Reply