What optimization does move semantics provide if we already have RVO?

前端 未结 8 1851
北海茫月
北海茫月 2020-12-04 17:50

As far as I understand one of the purposes of adding move semantics is to optimize code by calling special constructor for copying \"temporary\" objects. For example, in th

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 18:40

    Another good example I can think of. Imagine that you're implementing a matrix library and write an algorithm which takes two matrices and outputs another one:

    Matrix MyAlgorithm(Matrix U, Matrix V)
    {
        Transform(U); //doesn't matter what this actually does, but it modifies U
        Transform(V);
        return U*V;
    }
    

    Note that you can't pass U and V by const reference, because the algorithm tweaks them. You could theoretically pass them by reference, but this would look gross and leave U and V in some intermediate state (since you call Transform(U)), which may not make any sense to the caller, or just not make any mathematical sense at all, since it's just one of the internal algorithm transformations. The code looks much cleaner if you just pass them by value and use move semantics if you are not going to use U and V after calling this function:

    Matrix u, v;
    ...
    Matrix w = MyAlgorithm(u, v); //slow, but will preserve u and v
    Matrix w = MyAlgorithm(move(u), move(v)); //fast, but will nullify u and v
    Matrix w = MyAlgorithm(u, move(v)); //and you can even do this if you need one but not the other
    

提交回复
热议问题