Search code examples
c++11move-semanticsrvalue-reference

How to localize places for introducing move semantics in a legacy code base?


We have a pretty huge code base, sometimes with performance issues. Move semantics is not used at all. I am wondering how could I find places where move semantics might be useful. Do you have any experience how to localize such a places?


Solution

  • Move construction is a great feature because once you add a move constructor you get all the performance benefit "for free". Sure, you can explicitly move objects, but many uses of the move constructor are actually implicit.

    Some places (far from an exhaustive list) that benefit once you add a move constructor to a class would be:

    std::vector<T> vec;
    vec.push_back(T());                //implicit move into array
    std::sort(vec.begin(), vec.end()); //may move if std::swap performs swap
    T obj = foo();                     //move construct if compiler doesn't apply RVO
    T obj2 = obj + T();                //technically same as the line above
    

    The great part about it is that once you add a move constructor to the class (usually only a few lines of code) you don't have to change ANY other code to start reaping the benefits of move!

    Your biggest gains would most likely be in loops adding elements to containers, but you get an improvement in all of these areas just by adding a move constructor (which is often trivial to write).

    However, 99% of the classes that will benefit from move are classes which allocate memory or resources, because move allows you to replace a deep copy with a shallow copy. Most other classes (such as classes that are just record types) don't gain anything from move.