What is std::move(), and when should it be used?

后端 未结 8 1980
粉色の甜心
粉色の甜心 2020-11-22 08:27
  1. What is it?
  2. What does it do?
  3. When should it be used?

Good links are appreciated.

8条回答
  •  悲哀的现实
    2020-11-22 08:53

    std::move itself doesn't really do much. I thought that it called the moved constructor for an object, but it really just performs a type cast (casting an lvalue variable to an rvalue so that the said variable can be passed as an argument to a move constructor or assignment operator).

    So std::move is just used as a precursor to using move semantics. Move semantics is essentially an efficient way for dealing with temporary objects.

    Consider Object A = B + C + D + E + F;

    This is nice looking code, but E + F produces a temporary object. Then D + temp produces another temporary object and so on. In each normal "+" operator of a class, deep copies occur.

    For example

    Object Object::operator+ (const Object& rhs) {
        Object temp (*this);
        // logic for adding
        return temp;
    }
    

    The creation of the temporary object in this function is useless - these temporary objects will be deleted at the end of the line anyway as they go out of scope.

    We can rather use move semantics to "plunder" the temporary objects and do something like

     Object& Object::operator+ (Object&& rhs) {
         // logic to modify rhs directly
         return rhs;
     }
    

    This avoids needless deep copies being made. With reference to the example, the only part where deep copying occurs is now E + F. The rest uses move semantics. The move constructor or assignment operator also needs to be implemented to assign the result to A.

提交回复
热议问题