Skip to main content

C++11 - Auto type

At the beginning I would like to explain you one small new feature of C++11 standard. This feature is auto type.
auto is new C++11 type keyword which automatically deducts type of variable.
See example below:
What is type of variable b?  int of course. C++11 can automatically deduct type of variables using auto type. However remember - there is not desirable to use auto too often. It can make your code less readable. Try to use defined types as often as possible.
Nevertheless, there is little more useful example of usage auto type. Let say that we have been declared following map containing two strings as key-value instances:
Now if we would like to iterate through elements of above map in previous version of C++ (C++03) we had to declare iterator following way for example:
Thanks to auto type C++11 allow us to declare it that way:
Shorter and more comfortable.
That's it for the beginning. I hope you understand usage auto type in C++11 right now. Write your proposition of other ways of usage auto type in comments, please.

Comments

Popular posts from this blog

Blog's new layout

As you noticed this blog has new layout from today. I hope you like it. I think new layout looks better and more modern than previous one. Please, write you opinion about new layout in comments. If you have some ideas how to make this blog better, all ideas are welcomed. Enjoy new layout and blog articles.

QT - foreach algoriithm with const references performance improvement

Today I would like to show you optimal way of using foreach QT algorithm . I will show you why we should pass elements of foreach algorithm by const reference instead of passing them by value. Let me explain it on the below example: Output of this example is: In point I we are creating 3 objects of MyClass class and push them to myClasses QList element. In point II we are using QT foreach algorithm to invoke getValue() method for each object from myClasses list. As you can see on output text for that part of code we are invoking copy constructor before and destructor after invoking getValue() function. It is because we are passing each myClasses list element to foreach algorithm by value. Therefore we are copying that element at the beginning of foreach loop step and removing them (destructing) at the end. This is inefficient solution, especially when class of object being copied is big. It decreases performance. of our application. Solution for that i...

C++ in 2014 - Predictions

Today I would like to share with you interesting article about prediction of development C++ programming languages (and its well-known frameworks and libraries) in 2014. It is written by Jens Weller and I think it is very interesting for every C++ programmer and user. You can open this article by clicking on the image below: Enjoy!