"Dr. J.K. Becker" <> writes:
> Hi all,
>
> I have vectors that holds pointers to other vectors, like so:
>
> vector<whatever> x;
> vector<whatever*> z;
>
> z=&x;
This is a compiler error.
>
> Now I add something to x
>
> x.push_back(something);
>
> Will all the pointers in z still be valid?
Iff push_back() causes a reallocation then all pointers, references,
and iterators which refer to an element of the container are
invalidated. A reallocation occurs if size() == capacity() at the
time of the push_back(). You can use reserve() reserve enough
capacity to do a number of push_pack()s.
Example:
#include<vector>
int main()
{
std::vector<int> v;
//reserve(2) guarantees at least enough space for 2 elements to be
//added to v before reallocation.
v.reserve(2);
v.push_back(1);
int* foo= &v[0];
v.push_back(2);
//at this point, foo is still valid.
if (v.capacity() == v.size())
{
v.push_back(3);
//The 3rd push_back exceeded capacity, so
//it invalidated foo.
*foo; //undefined behavior.
}
else
{
v.push_back(3);
//In this case, v.capacity() is at least 3, so push_back does
//not force a reallocation, and foo is still valid.
*foo; //defined behavior.
}
}
Note that reserve() itself will trigger a reallocation iff the
requested size is greater than the current capacity.
My example uses pointers, but for vector, the same rules apply to
iterators and references as well.
> Of course I have problems with
> something like this and I think not, but I didn't find anything that says
> if, on using push_back, the vector allocates new memory for the whole
> vector or if it just allocates new memory for the stuff that is added.
> Also, I read that if you have vectors in vectors like so:
>
> class x
> {
> vector<whatever> z;
> }
>
> and then
> vector<x> vec;
If this (common) usage results in memory leaks, you have a badly
broken implementation. Where I work, we use 3 different versions
of gcc, MSVC++ 2003, and hp aCC, and none of them have trouble
with constructs like this.
> That this often causes problems with keeping track of memory therewith
> causing memory leaks? If so, is there a better way to do it?
[snip]
|