10

I found in a post how to delete elements from a container using an iterator. While iterating:

for(auto it = translationEvents.begin(); it != translationEvents.end();)
    {
        auto next = it;
        ++next; // get the next element
        it->second(this); // process (and maybe delete) the current element
        it = next; // skip to the next element
    }

Why is auto used without the type in auto next = it;?

I use VS10,not C++11 !

Chris
  • 4,663
  • 5
  • 24
  • 33
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

4 Answers4

18

auto has a different meaning in C++11 than it did before. In earlier standards, auto was a storage specifier for automatic storage duration - the typical storage an object has where it is destroyed at the end of its scope. In C++11, the auto keyword is used for type deduction of variables. The type of the variable is deduced from the expression being used to initialise it, much in the same way template parameters may be deduced from the types of a template function's arguments.

This type deduction is useful when typing out ugly long types has no benefit. Often, the type is obvious from the initialiser. It is also useful for variables whose type might depend on which instantiation of a template it appears in.

Many C++11 features are supported by default in VC10 and auto is one of them.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
5

It is a short-hand in newer versions of C++ that allows us to avoid the clunky iterator notation, since the compiler is able to infer what the actual type is supposed to be.

Chris
  • 4,663
  • 5
  • 24
  • 33
4

It's called Type Inference, see also this question for details. New in C++11, and intended to simplify many long and unnecessary codes, especially for iterators and function bindings.

Community
  • 1
  • 1
lucas clemente
  • 6,255
  • 8
  • 41
  • 61
3

This is called type inference. The type of the auto variable is deduced by the type of the initializer.

E.g., this reduces the amount to type for large and complicated template types.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198