Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the benefits of move semantics vs template metaprogramming

I've read some descriptions about move semantics in C++11 and I wonder in what context it could be used. Currently, many C++ math libraries use template metaprogramming to delay evaluation.

If M = A + B + C*D, where M, A, B, C and D are matrix, template metaprogramming allow to avoid useless copies. Is move semantics a more convenient manner to do these sort of things ?

If not, in what context move semantics is used. If yes, what are the difference/limitations compared to template metaprogramming for that kind of use ?

like image 744
Vincent Avatar asked May 23 '12 17:05

Vincent


1 Answers

I believe a more precise term for what you're calling "template metaprogramming" is expression templates.

If your matrices allocate their data dynamically, move semantics can help transfer that data from object to object (including to/from the temporaries) generated during an expression such as:

M = A + B + C*D

Expression templates, on the other hand, will eliminate the temporaries entirely.

If your matrices do not allocate their data dynamically (e.g. if they are fixed size and small), move semantics will not aid your performance at all.

The application of expression templates to a matrix library will result in the highest performance. It is also a very difficult implementation technique. Move semantics is much easier to implement, and can be done in addition to expression templates (if there are resources such as memory that can be transferred).

In summary:

Move semantics does not eliminate temporaries, but will transfer dynamically allocated memory among the temporaries instead of re-allocating it.

Expression templates eliminates the temporaries.

like image 53
Howard Hinnant Avatar answered Oct 22 '22 13:10

Howard Hinnant