Template trick to optimize out allocations

前端 未结 3 696
南旧
南旧 2021-02-03 11:20

I have:

struct DoubleVec {
  std::vector data;
};

DoubleVec operator+(const DoubleVec& lhs, const DoubleVec& rhs) {
  DoubleVec ans(lhs.si         


        
3条回答
  •  野的像风
    2021-02-03 11:52

    Yep, that's exactly what expression templates (see http://www.drdobbs.com/184401627 or http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Expression-template for example) are for.

    The idea is to make operator+ return some kind of proxy object which represents the expression tree to be evaluated. Then operator= is written to take such an expression tree and evaluate it all at once, avoiding the creation of temporaries, and applying any other optimizations that may be applicable.

提交回复
热议问题