Re: Sequence container capacity after calling clear()
In article <85745c86-b880-462e-ab3f-ac6cb16b1dd5@googlegroups.com>,
goran.pusic@googlemail.com () wrote:
On Monday, March 25, 2013 7:40:02 PM UTC+1, Leigh Johnston wrote:
To see how it might affect portability consider how reallocations
invalidate iterators and element references.
That's what I thought one might think of, but (AFAIK)
* there is no guarantee whatsoever that an iterator that used to
"point" to an element, then stopped to point to it (because
vector was cleared) can become valid again when vector is filled
back up.
* I can't see how holding references to destroyed objects can be a
good idea.
That's not what Leigh means. Instead consider:
{
std::vector<int> v( 10 );
assert( v.size() == 10 && v.capacity() == 10 );
v.clear();
assert( v.size() == 0 && v.capacity() == 10 );
v.push_back( 1 );
std::vector<int>::iterator i = v.begin();
v.push_back( 2 );
cout << *i;
}
If clear() does not change capacity and both asserts are true, then
the iterator will still be valid after the final push_back(). If not,
not. For reasonable code, it matters.
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]