• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++/STL question

Turkey

Senior member
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?
 
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);
 
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?
 


<< 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( ));

 
Back
Top