0
votes

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);
}
1
This static_cast<T&&>(x) is more commonly spelled as std::move(x). Googling it should give you better results. - HolyBlackCat

1 Answers

0
votes

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.