Beware of auto[&] (c++)
auto
deduces its types from initializing expressions, and occasionally, these expressions have unexpected types, which are not what you want. On the other hand, auto has many benefits. - Don’t use C++ auto?
int& f();
auto a = f(); // BEWARE! a => is int
auto& a = f(); // a => is int&
int x = 0;
int& r = x;
const int& cr = x;
const auto& v = x; // v’s type is “const int&”; auto is “int"
const auto& cv = cr; // cv’s type is “const int&”; auto is “int"
auto* w = &r; // w’s type is “int*”; auto is “int"
auto* cw = &cr; // cw’s type is “const int*”; auto is “const int”
std::vector<int> vec({1, 2, 3, 4, 5});
auto& first = vec[0]; // first's type is "int&”; auto is “int”
Written on February 1, 2018, Last update on September 23, 2020
c++