Saturday, January 4, 2014

5 reasons to start using C++11

Get performance benefits
#1
The hash tables which have now become standard provide faster insertion, deletion and lookup than their ordered counterparts, which can be very useful when handling large amounts of data. You now have unordered_map, unordered_multimap, unordered_set and unordered_multiset at your disposal.

#2.
With the use of type traits (e.g. is_floating_point) and template metaprogramming (e.g. the enable_if template), you can specialize your templates for types with particular characteristics and thus implement optimizations.

#3.
Lambda expressions provide a way to define anonymous function objects (which are actually closures) right where they are used, thus making the code more linear and easier to follow. This is very convenient in combination with STL algorithms:
bool is_fuel_level_safe()
{
    return all_of(_tanks.begin(), _tanks.end(),
        [this](Tank& t) { return t.fuel_level() > _min_fuel_level; });
}
also The new smart pointers which have replaced the problematic auto_ptr allow you to stop worrying about memory cleanup, and to remove the cleanup code. It’s good for clarity, and for avoiding memory leaks and the associated time spent to hunt them down.

#4.
To explain the concept very briefly, it’s a way to optimize copying. Sometimes copying is obviously wasteful. If you’re copying from a temporary string object, simply copying the pointer to the character buffer would be much more efficient than creating a new buffer and copying the character. It would work because the source object is about to go out of scope.
However, previously there was no mechanism in C++ to figure out whether the source object is a temporary or not. Move semantics provide this mechanism by allowing you to have a move constructor and a move assignment operator in addition to the copy operations.
Did you know that if you’re using classes from the standard library like string or vector in Visual Studio 2010, they already support move semantics? This helps prevent unnecessary copying and therefore improve performance.
By implementing move semantics in your own classes you can get additional performance improvements, for example when you store them in STL containers. Also, keep in mind that move semantics can be applied not only to constructors, but also to methods (such as vector‘s push_back).

#5.
Having functions as first class objects is a very powerful feature that allows your code to be flexible and generic. C++11 makes a step in this direction with std::function. function provides a way to wrap and pass around anything callable – function pointers, functors, lambdas and more. 

No comments:

Post a Comment