Learning C++11 (Part 1)

Background

As a long time C/C++ programmer I thought it was time to delve into some of the newer features of C++ now that Visual Studio 2015 offers full support and the team is making wider use. The purpose is to be able to understand code that is already written and to be more effective in my own code.

auto keyword (or type inference)

The first thing I wanted to understand is the auto keyword. Very simply, using auto adds the ability to infer the type of a variable. I immediately gravitated towards a couple of use cases.

Old C++

  for (std::vector<int>::const_iterator itr = v.cbegin(); itr != v.cend(); ++itr)

C++11

  for (_auto_ itr = v.cbegin(); itr != v.cend(); ++itr)

Using auto to infer the verbose syntax of iterators or other templated code increases code readability.

Old C++

  SomeNamespace::MyClass::SomeEnumType rv = myclass.someFunction();

C++11

  _auto_ rv = myclass.someFunction();

Use can also use auto to infer the return type of a function. Especially when it's not useful to see the return type spelled out. Simplifying the code with no loss of clarity. This also comes in handy if the return type is some kind of integer but you don't really care what size or sign it is (like from some kind of size() function). But be careful if you do care about size or sign (like when you're bit twiddling).

Best advice I was offered was to use auto as much as possible and then see where things break or if code becomes harder to read. The auto keyword replaces code that already works so use it as much as you're comfortable with.

-- Garner Halloran (Engine Programmer)