Home > Blockchain >  Copying variables, creating temporary variables and move semantics
Copying variables, creating temporary variables and move semantics

Time:10-18

I was learning about move semantics and rvalue references when I came across this web page https://www.open-std.org/JTC1/SC22/WG21/docs/papers/2006/n2027.html. There is a piece of code that confuses me.

Without move semantics

template <class T> swap(T& a, T& b)
{
    T tmp(a);   // now we have two copies of a
    a = b;      // now we have two copies of b
    b = tmp;    // now we have two copies of tmp (aka a)
}

With move semantics

template <class T> swap(T& a, T& b)
{
    T tmp(std::move(a));
    a = std::move(b);   
    b = std::move(tmp);
}

How can we perform two copies of a b and tmp. Specially a and b since they are passed by reference.

CodePudding user response:

Let a' and b' be the values in a and b before the function.

template <class T> swap(T& a, T& b)
{
  T tmp(a);   // now we have two copies of a' (in a and tmp) and one of b' (in b)
  a = b;      // now we have two copies of b' (in a and b) and one of a' (in tmp)
  b = tmp;    // now we have two copies of a' (in b and tmp) and one of b' (in a)
}

that might help.

Then we do the move version:

template <class T> swap(T& a, T& b)
{
  T tmp(std::move(a)); // a' is in tmp; b' is in b; a is moved-from
  a = std::move(b);    // a' is in tmp, b' is in a; b is moved-from
  b = std::move(tmp);  // a' is in b; b' is in a; tmp is moved-from
}

the trick is to distinguish between the variable a and the value stored in a.

  • Related