Keyword ' auto`

What does the keyword auto mean in c++ and where does it apply?

 10
Author: αλεχολυτ, 2015-01-05

2 answers

This word is redefined in the new standard and tells the compiler: "Compiler, take and guess the type of this variable!". The compiler can do this very well in many cases. This is useful in templates and for iterators.

Once upon a time, this word meant something completely different.

 8
Author: KoVadim, 2016-05-08 09:45:17

Stone Age

The auto keyword means that the variable is in automatic storage and the lifetime of such a variable is local lifetime. In other words, we indicated that this variable lies on the stack, but since all variables created in functions are like

int a = 10;

Already it is implied that they are stack-based-then this keyword is meaningless.

Starting with C++11

Starting with C++11, the auto keyword takes on a new life. It says that the compiler at compile time, must determine the type of the variable based on the type of the expression being initialized.

#include <iostream>
#include <typeinfo>
#include <vector>
using namespace std;

class Foo
{
public:
    Foo( int x )
    {

    }
};
int main()
{
    std::vector<std::vector<Foo*>> arr;

    auto a = 166LL;
    auto b = 'a' + true;
    auto c = Foo(3);
    auto d = arr.begin();


    cout << typeid(a).name() << endl;
    cout << typeid(b).name() << endl;
    cout << typeid(c).name() << endl;
    cout << typeid(d).name() << endl;
    return 0;
}

Output: http://rextester.com/BNNAL62867

Features of auto

  1. The auto variable must be explicitly initialized
  2. The auto variable cannot be a member class
  3. The auto variable cannot be a function parameter until C++14
    http://ideone.com/n7dZge
  4. The auto type cannot be the return type of the function before C++14. http://rextester.com/AFDFD63587

Holivar

Supporters of: there are data types in C++ that spoil the readability when they are long (about std iterators::vector, for example) and I would like to write less. For modern C++, under metaprogramming conditions, the ability to return the auto type makes the template flexible.
Opponents : the auto type affects the readability of the code. We have to guess what the variable is and do it an extra action in the IDE is hovering the mouse to understand what type it is. This kind of "dynamic type" goes against the definition that C++ is a strongly typed language.

I'm all for using auto in moderation. Don't go to extremes.

 11
Author: rikimaru2013, 2016-05-07 22:05:44