Using std::move() when returning a value from a function to avoid to copy

前端 未结 3 1264
-上瘾入骨i
-上瘾入骨i 2020-12-01 04:45

Consider a type T supporting the default move semantics. Also consider the function below:

T f() {
   T t;
   return t;
}

T o = f();

In th

3条回答
  •  心在旅途
    2020-12-01 05:50

    Ok, I would like to drop a comment on this. This question (and the answer) made me believe that it is not necessary to specify std::move on the return statement. However I was just thought a different lesson while dealing with my code.

    So, I have a function (it's actually a specialization) that takes a temporary and just returns it. (The general function template does other stuff, but the specialization does the identity operation).

    template<>
    struct CreateLeaf< A >
    {
      typedef A Leaf_t;
      inline static
      Leaf_t make( A &&a) { 
        return a;
      }
    };
    

    Now, this version calls the copy constructor of A upon returning. If I change the return statement to

    Leaf_t make( A &&a) { 
      return std::move(a);
    }
    

    Then the move constructor of A gets called and I can do some optimizations there.

    It might not be 100% matching your question. But it is false to think that return std::move(..) is never necessary. I used to think so. Not any more ;-)

提交回复
热议问题