Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-07-07 05:58:34


jhopkin_at_[hidden] wrote:
> Daniel Frey wrote:
>> jhopkin_at_[hidden] wrote:
>>> The STL implementation I have been using seems to allocate a buffer
>>> on first insertion into any container of a given type, and frees it
>>> only when it feels like it (often on program shut-down).
>>
>> Sounds like a pool allocator. Question: Does .clear() for your STL
>> return the buffer to the pool or is it still bound to the instance?
>> What happens in case of the .swap()-trick?
>
> I believe .clear() and the swap trick do what's expected per instance.
> Specifically for vector, clear generally won't release any memory to
> the pool; the swap trick releases it all.

The swap trick is almost guaranteed to reduce the capacity to an
implementation-defined minimum value, unless the original vector has size()
== 0 && capacity() != 0, in which case lhs.swap( rhs ) can detect lhs.size()
== rhs.size() == 0 and do nothing. ;-) That's the theory, of course, in
practice the swap() trick always works.

In standard-conforming implementations, clear() does not change the
capacity. In the Dinkumware STL, however, it releases the memory and sets
capacity() to 0.

All this means that, in portable code:

- V().swap(v); should be used to reduce capacity to about zero.

- v.erase( v.begin(), v.end() ); should be used to set size to zero, leaving
capacity unchanged.

- v.clear() should not be used if v will be repopulated and
portability/performance is a concern, until Dinkumware fix their STL.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk