As 0A0D mentions, the effect of swap
is to exchange the underlying controlled memory between the two vectors. But this warrants a little more explanation.
When you clear
a vector
, the elements are removed from it at least as far as the programmer is concerned. size()
becomes zero and capacity()
may or may not change. But the Standard doesn't guarantee that the memory used by the vector will actually be returned back to the operating system. So if you had 1000 elements in the vector before the clear()
and each took 1000 bytes memory, after the clear()
each element's destructor is called, but the vector may still be holding on to a 1,000,000 byte allocation.
This is sometimes undesirable. The 'swap trick' you note above has the effect of exchanging the controlled memory between the two vectors. Hence decoy
ends up with it's controlled memory reset.
Here is what is happening step-by-step:
decoy
elements are each erased
.
The elements' destructors are
called, and the vector's size()
becomes zero. The actual memory may
not be deallocated.
- A new vector is constructed on the stack (
vector<weight> (decoy)
) and the elements from decoy
are copied in to it. Since decoy
was just clear()
ed, no elements are copied in to the temporary vector. However, see edit below. You don't know that the controlled memory is not swapped.
- The temporary vector's and
decoy
's memory are swapped (.swap(decoy);
) resulting in decoy
being both cleared and it's memory transferred to the temporary.
- The temporary falls off the stack, resulting in it's memory being deallocated.
This is referred to as "the swap trick".
EDIT: As Mike mentions, the original programmer is doing it wrong. The temporary should not be constructed based on decoy
, it should just be default constructed. You don't know for sure that swap()
will only copy the elements and not the controlled memory underneath.