The C++0x Auto Keyword
Sunday, 12 June 2011 11:07
SFMLCoder/Zephyr
As you may know, C++0x has taken the old, defunct auto keyword and completely repurposed it to perform a useful task. Forget what auto did before - it's the default behaviour or variables anyway, so it's unnecessary. Focus on it's new meaning. So what does auto do now? Well you can declare a variable with the auto keyword instead of a type specifier such as int or double or std::string. Then, the compiler deduces the type of this variable from its initializer. So, auto x = 4 would make x an integer, as the compiler deduces its type from the type of 4. Note, therefore that a variable declared with auto must have an initializer. if it doesn't, you will get a compiler error, as it cannot deduce the variable's type. Clearly, this can ease development somewhat, but we must now discuss the right and wrong circumstances in which auto should be used. You should not use auto when the variable type is obvious. This will just result in messy, hard-to-read code, and it doesn't really save any time - int is shorter than auto! A good circumstance to use auto is one in which writing out the type would be time consuming, or poorly maintainable, for example for an STL iterator. This is how we'd normally do things: std::map addressBook; As you can see, writing down the iterator is a pain. What if we did this: std::map addressBook; The compiler deduces the type of itr from the type of addressBook.begin(), and suddenly it wasn't so difficult to write the iterator. Also, if we later change the template arguments of the map, we don't have to update the iterators, since the compiler will now deduce the new type for them. If you want to read more about auto, you can see Dr. Stroustrup's FAQ, or read my blog post on it (where I have a full code example). |
|||||||||||||||||||||||
|
What should be added to C++Org next? | ||||||||||
|
||||||||||
|