samedi 1 octobre 2022

Copying variables, creating temporary variables and move semantics

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.

Aucun commentaire:

Enregistrer un commentaire