Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

c++ - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...