C++/STL question

Turkey

Senior member
Jan 10, 2000
839
0
0
I've got a bunch of STL containers that all contain structured data. Then I've got some other STL containers that contain pointers to the first set of containers. Each set of containers is being built dynamically, so they are both getting resized during the course of the program. Does the resizing in the first set of containers invalidate the pointers in the second set?
 

PCHPlayer

Golden Member
Oct 9, 2001
1,053
0
0
If you are doing the following you are fine:

class A {
...
};

vector<A> vec1;
vector<A> vec2;
vector<vector<A> * > vec_of_vecs;

vec_of_vecs.push_back(&vec1);
vec_of_vecs.push_back(&vec2);
 

Turkey

Senior member
Jan 10, 2000
839
0
0
Oops, explained it wrong :)

What I'm doing is this:

class A {
...
int data1;
}

vector<A> vec1;
vector<A*> vec2;

A obj1;
vec1.push_back(obj1);
vec2.push_back(&vec1.at(vec1.size() - 1)); // creating a pointer to the object stored I just stored in vec1

So I'm concerned that when vec1 exceeds its initial allocation and its memory gets reallocated, will vec2[0]->data1 still have the proper data? And if not, could I use some other STL container (list, queue) that would make vec2[0]->data1 have the proper data?
 

HigherGround

Golden Member
Jan 9, 2000
1,827
0
0


<< So I'm concerned that when vec1 exceeds its initial allocation and its memory gets reallocated, will vec2[0]->data1 still have the proper data? >>



no, you will not. You are holding a pointer to a copy of you object ( not the object itself ), so if vector decides to move internal storage ( usually array ) to another location, you will be pointing to a freed memory. One way to get around that is to store pointers to objects in both vectors, but than you have to agree which containrer is responsible for their deallocation, the code would look something like that ....


vector<A*> va1;
vector<A*> va2;
va1.push_back(new A);
va2.push_back(va1.back( ));