I was looking for how to erase the front element of an std::vector object, and I found the following code here.
template<typename T>
void pop_front(std::vector<T>& vec)
{
assert(!vec.empty());
vec.front() = std::move(vec.back());
vec.pop_back();
}
As far as I understand, it moves the object at the back (assuming that the contained object is movable) to the front. The object at the back is now empty, and the object at the front is lost since it is overwritten. Then, it detaches the back element, leaving the front one overwritten with the lost back one.
But appearently, it doesn't happen like I said. The documentations says that the front() and back() objects return references. If they did return pointers or iterators and we swapped them, or we swapped the back and front objects with std::swap(), I could understand it. But in this code, it just looks like we overwrite the front element.
Can you please explain me how it works?