The auto keyword and the range-based for loop take away a lot of the typing that used to be necessary in C++, and they make the code read more cleanly. But there is a right way and a wrong way to use them, and the difference comes down to whether you are still saying what the type is.
The previous lesson in this module covered "How Do Templates Write Code Once for Many Types?", and the next lesson in this module is about "How Do Lambdas Capture and Express Behavior Inline?".
auto names the type for you
Before C++11 the type of a variable had to be written out, and that was painful with the long types.
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::map<std::string, std::vector<int>> readings;
readings["oil"] = {42, 43, 44};
for (const std::pair<const std::string, std::vector<int>>& entry : readings) {
std::cout << entry.first << ": " << entry.second.size() << " values\n";
}
return 0;
}The output shows the nested type being spelled out twice.
oil: 3 valuesAnd with the auto the type is deduced from the initialiser.
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::map<std::string, std::vector<int>> readings;
readings["oil"] = {42, 43, 44};
for (const auto& entry : readings) {
std::cout << entry.first << ": " << entry.second.size() << " values\n";
}
return 0;
}The three forms of auto
There are three forms, and they differ in what they do with the value.
the form what it does
-------------------------- ---------------------------------------------
auto value = expression; makes a copy
auto& reference = expr; binds a reference, so it can be changed
const auto& value = expr; binds a const reference, which is what
you usually want
#include <iostream>
#include <string>
int main() {
std::string original = "measured";
auto copy = original;
auto& reference = original;
const auto& const_reference = original;
copy += " (copy)";
reference += " (reference)";
// const_reference += " (ignored)"; // does not compile: it is const
std::cout << "original: " << original << '\n';
std::cout << "copy: " << copy << '\n';
std::cout << "reference: " << reference << '\n';
std::cout << "const_reference: " << const_reference << '\n';
return 0;
}The output shows exactly what each one did.
original: measured (reference)
copy: measured (copy)
reference: measured (reference)
const_reference: measured (reference)The range-based for loop
The range-based for loop was introduced in C++11, and it replaces the old loop with the iterator and the end().
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::vector<std::string> parcels = {"p-001", "p-002", "p-003"};
for (const std::string& parcel : parcels) {
std::cout << parcel << ' ';
}
std::cout << '\n';
std::map<std::string, int> counts = {{"north", 3}, {"south", 5}};
for (const auto& [zone, count] : counts) {
std::cout << zone << '=' << count << ' ';
}
std::cout << '\n';
return 0;
}The output shows both of the loops working, and the second one using a structured binding to name the key and the value.
p-001 p-002 p-003
north=3 south=5What auto is good for
The auto is at its best in three places. The first one is the long type names, where spelling it out adds nothing. The second one is the iterators, where the type is long and the meaning is not. And the third one is the template parameters, where the type is a parameter of the function and so it cannot be written down at the call site.
the situation use auto
------------------------------------ -----------------------------------
the type name is long and obvious yes
the type is an iterator yes
the type is a template parameter yes
the value is a plain int or a bool no, write the type
you want the reader to see the type no, write the type
What auto is bad for
The auto is bad when it hides the type that the reader needs to see. So a function that returns auto tells the reader nothing about what it gives back, and that is worse than the old style in a public interface. And a variable of type auto that holds a plain integer says nothing more than the word int would.
And there is a practical trap that is worth knowing about. The auto always deduces the type from the initialiser, so auto x = 0; gives you an int and not a pointer. If you wanted a pointer you have to write int* x = nullptr; by hand.
decltype(auto)
The decltype(auto) deduces the type the way that decltype would, which means that it preserves the references and the top-level const.
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> parcels() {
return {"p-001", "p-002"};
}
int main() {
const auto& safe = parcels(); // a reference to a temporary, extended
decltype(auto) by_value = parcels(); // a copy of the vector
std::cout << "safe size: " << safe.size() << '\n';
std::cout << "by value: " << by_value.size() << '\n';
return 0;
}The output shows both of them holding the same two elements.
safe size: 2
by value: 2Quick reference
- The
autodeduces the type from the initialiser. - The plain
automakes a copy, theauto&binds a reference and theconst auto&binds a const reference. - The range-based for loop is the old iterator loop written more readably.
- Use the auto for the long types, and write the type out when the reader needs to see it.
- The
decltype(auto)preserves the references and the top-level const. - The
autonever deduces a pointer from a literal zero.
Try it yourself: write a function that takes a vector of the long type name and gives back the size of the largest one, and try it with the type written out and with the auto. Then write a range-based for loop over a map of the strings to the integers and print the entries. Finally, write a small function that returns an auto and check what the reader of the call site can work out about it.