Mike Wahler said:
Actually, I didn't mean either one.
I meant:
std::swap(*v, std::vector<int>());
Note that this illegal, for the same reason as the
first example ( v->swap(std::vector<int>()) ).
std::vector<int>() is a temporary, and both of the swap
calls you suggested expect a non-const reference as a
first parameter.
This is unlike the valid option:
std::vector<int>().swap(*v); // this is ok
Here swap is invoked as a member function of the
temporary, which is legal ISO C++.
AFAIK, it *will* free the memory occupied by
its elements (assuming of course that if the
elements are UDT's which manage memory, they do so
correctly).
The standard mandates that v.clear() is equivalent to
calling v.erase( v.begin(), v.end() ) -- in 23.1.1.
The erase function does not cause the vector's memory
to be reallocated (or freed). Its effect is to (23.2.4.3)
invalidate "all the iterators and references *after* the
point of the erase". Which means that the iterator
returned by v.begin() shall not be invalidated by the
call to v.clear().
Basically, clear() will set the *size* of a vector to 0,
but will leave the *capacity* of the vector unchanged.
The memory block that std::vector has allocated to
store its contents will not be freed.
Can you elaborate, please?
v1.swap(v2) will exchange the memory blocks that are
associated with the two vectors. This is typically done
by swapping the pointers stored within each vector.
When using: std::vector<int>().swap(*v);
std::vector<int>() typically does not allocate any
memory (its capacity is zero). After the memory blocks
are exchanged, v will receive the block of capacity 0,
and the temporary owns the memory previously associated
with v -- which will be released by the temporary's
destructor.
Well, I hope this is not too confused... it's getting
late here.
Sincerely,
Ivan