In C++11, auto
has new meaning: it allows you to automatically deduce the type of a variable.
Why is that ever useful? Let's consider a basic example:
std::list<int> a;
// fill in a
for (auto it = a.begin(); it != a.end(); ++it) {
// Do stuff here
}
The auto
there creates an iterator of type std::list<int>::iterator
.
This can make some seriously complex code much easier to read.
Another example:
int x, y;
auto f = [&]{ x += y; };
f();
f();
There, the auto
deduced the type required to store a lambda expression in a variable.
Wikipedia has good coverage on the subject.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…