söndag 17 oktober 2010

2 reasons for emebedded devs to use a C++0x-enabled compiler

C++0x introduces a lot of really neat things that any developer have use of (many that come from Boost). For example, proper auto-pointers (std::shared_ptr and std::weak_ptr), a new std::function that plays well with std::bind, and the auto keyword for automatic typing at initialization, are all applicable in most C++projects.

But many embedded programmers don't feel to strongly for using "modern" C++ features (like templates) or the STL library, due to concerns over code bloat or performance issues (Microsoft's earlier implementation of STL had some issues with performance, for example in std::string).

However, there are at least two reasons for embedded devs to start looking at C++0x when thinking code size/performance optimization.

Rvalue references (link)
C++ is generally overly fond of copying data, even at times it's not strictly nessecary. To mitigate this, C++0x adds the rvalue reference, denoted by T&&, which enables move sematics.

For example, if you return a std::vector<int> from a function in C++03, a temporary object will have to be created and deleted. This will result in a deep copy of an int array which is used by std::vector internally. In C++0x, by implementing a move-constructor, std::vector can copy only the pointer to the internal C array, in cases where the rvalue (the temporary) is not needed, This is enabled by declaring the return type of your function as std::vector&&.

In some cases, this can lead to a big performance boost, as new and delete are typically expensive on embedded systems. This guy found that using rvalues when sorting vectors containing PODs could double the performance.

Of course, C++0x versions of STL will implement rvalue references and move-constructors where applicable, like in std::vector.

Extern templates (link)
Okay, even though this was not in the standard, many compiler vendors already implemented this in C++03. However the feature was not so well-known (at least not to me).

Consider you have many translation units, like multiple libs. It is not uncommon to instantiate some identical templates in more than one lib. There is no guarantee that the compiler will optimize away the redundant instantiation, which may cause code bloat and longer compile time.

By declaring the template extern:

extern template std::vector<int>;

you tell the compiler not to instantiate the template in this translation unit. Obviously, this requires that the template is instantiated somewhere else.

Inga kommentarer:

Skicka en kommentar