How much is too much with C++11 auto keyword?

Viewed 54856

I've been using the new auto keyword available in the C++11 standard for complicated templated types which is what I believe it was designed for. But I'm also using it for things like:

auto foo = std::make_shared<Foo>();

And more skeptically for:

auto foo = bla(); // where bla() return a shared_ptr<Foo>

I haven't seen much discussion on this topic. It seems that auto could be overused since a type is often a form of documentation and sanity checks. Where do you draw the line in using auto and what are the recommended use cases for this new feature?

To clarify: I'm not asking for a philosophical opinion; I'm asking for the intended use of this keyword by the standard committee, possibly with comments on how that intended use is realized in practice.

15 Answers

What auto does?

It tells compiler to infer(determine) the variable's data type based on its initialized value. It uses type deduction.

Where should auto be used?

  • When you are not interested in knowing the type of variable and just want to use it.

  • When you want to avoid incredibly long and ugly typenames.

  • When you are not sure of the type himself.

  • When you do not want to see uninitialized variables in your code i.e. auto forces you to initialize a variable hence you can’t forget doing that.

When it should not be used or Cons of auto

  • Referring to its functionality, auto may deduce type incorrectly, One such case is
 std::vector<bool> vec(10, 0);

 auto x = vec[2];

 bool y = vec[2];

 std::cout << typeid(x).name() << "\n";

 std::cout << typeid(y).name() << "\n";

The output on G++ 10.2 is surprising:

St14_Bit_reference

b
  • It should not be used if you want to make your code readable & Understandable for other people. It hides the data type visibility from the reader.
Related