The keyword auto in C++ (starting from C++11) allows the compiler to automatically infer the type of a variable from the initializing expression. This simplifies working with long types (for example, when dealing with iterators, lambdas, template expressions) and improves code readability.
Example of usage:
auto i = 42; // int auto d = 3.14; // double auto s = std::string("hi"); auto it = v.begin(); // iterator
However, auto infers the type exactly based on what it is "fed". For example, if returned by value, then auto will give a value, and if by reference — a reference. Care should be taken when dealing with references, pointers, and const qualifiers.
Important example:
std::vector<int> v = {1,2,3}; for (auto x : v) x = 0; // copying, v will not change for (auto& x : v) x = 0; // reference, elements will be zeroed
What type will the variable 'z' have in the expression
const auto z = foo();if the methodfoo()returns a reference to int (int&)?
Answer:
const auto z will infer the type as int (value), even if a reference is returned. To infer a reference, you need auto& z. The const qualifiers will be applied to the auto-type after type inference.
Example:
int x = 5; auto a = x; // a — int auto& b = x; // b — int& const auto c = x; // c — const int auto d = foo(); // d — int (if foo returns int) auto& e = foo(); // e — int&
Story
In a large web service, range-based for used auto instead of auto& on a collection of smart pointers. This led to copying objects, which slowed down the program by 16 times when processing millions of records.
Story
In a graph processing library, auto was applied to the returned iterator, expecting it to be a reference, but received a temporary object. The iterator was destroyed prematurely, causing the program to crash on UB after the loop.
Story
In a financial system, due to using auto to obtain a value from a map, they forgot about the constness of the key, which led to an attempt to modify data via a non-const reference, resulting in compilation errors and runtime crashes.