Home > Net >  What does this code do? (A question about rvalue references)
What does this code do? (A question about rvalue references)

Time:07-29

So I was reading "The C Programming Language" and this code got shown. How does it exactly work? I tried asking elsewhere, watching a video on references and another one on basic move semantics but I'm still insanely confused.

template<typename T>
void swap(T& a, T& b)
{
  T tmp {static_cast<T&&>(a)};
  a = static_cast<T&&>(b);
  b = static_cast<T&&>(tmp);
}

CodePudding user response:

This is used in order to employ move semantics, if possible, with these objects. If move semantics are not possible then this automatically devolves to plain, garden-variety, copy-based swapping. The capsule summary is as follows. If you look at plain, garden-variety swapping:

T tmp{a};

a=b;

b=t;

If these objects are "heavy" there's going to be a lot of copying going on. When you say a=b in C , you are making a complete duplicate of an object. If b is a vector with a million values, congratulations: you now have two vectors with a million values. And, as soon as you have them, one of them gets destroyed (in the process of swapping). A lot of work, all for nothing.

Move semantics avoid this needless overhead in situations that boil down to moving stuff around, in the end. Instead of creating a copy of an object it is "moved" directly from point A to point B, of sorts.

CodePudding user response:

Casting to T&& means movable reference. You could have the same effect via std::move(). Movable reference means the functions can have a different overload for this type. The required guarantee is that, after processing, the object that we 'move from' will remain in a valid-but-unspecified state. Sometimes it's way more effective than copying. E.g., for vectors, you might simply swap the buffers in a swap operation. The underlying operation here is T::operator=(T&&) that gets called.

  • Related