Thursday, August 11, 2011

auto (C++11)

The new C++11 standard has given us a lot new features. One of them is auto.
auto it is not exactly new, auto was actually already a reserved keyword in C++ but nobody used it. So auto now means something totally different and is now useful.

auto is like var is in C#. When you know that the compiler knows that type a variable should be, then you can use auto.

They are especially useful when you are writing or using templates.

I saw this ugly piece of code a while ago.
std::vector< std::pair<std::string, std::pair<int, long> > > vItems;
It is a pair inside a pair, inside a vector.

If you need to get the iterator for vItems in a variable you will get very messy code.
std::vector< std::pair<std::string, 
                       std::pair<int, long> 
              > >::iterator it =  vItems.begin();

Before C++11 I would have created a couple of typedef's for this instead to be able to handle it easier.
(Actually, I would have created an class instead that would hold string, int, long instead of creating that mess)

But with C++11 and the new auto keyword you do not have to do that.

With auto you just have to write.
auto it = vItems.begin();
So much easier.

auto can be used in places where you received a value, auto can not be used in the parameter list for a function. Functions must have specified types.

Don't over do it
As so much in C++, auto can be miss used. You can use auto all the time, and never declare a variable of the type you need, and rely on the compiler figuring it out for you. But this is really bad programming. You will end up with code that are hard to read and maintain, and it can also introduce bugs. Because you do not know what type something really is.

auto is required
There is one situation where you most use auto. It is if you create a lambda function that you assign to a variable. Since you never know what the type of the lambda is, since it is auto generated, auto must be used.

auto lam = [](int x) -> bool {
   if(x > 10)
     return true;
   return false;

  .. do stuff

Lambda expressions are also a new and really useful C++11 feature. But I'm not getting into that now.

No comments:

Post a Comment