q: stl vector of pointers / pointer consistancy

L

laniik

Hi. I have a question. If I have a vector of objects and on of object
pointers:

---
vector <Obj> objects;
vector <Obj*> objectPointers;
---

and i setup the vectors with somhthing like:

---
Obj o;
objects.push_back(o);
objectPointers.push_back(&objects[objects.size()-1])
---

now. when i grow the objects array:

---
for(int i=0;i<10000;i++)
{
Obj o;
objects.push_back(o);
}
---

is it possible that the pointer in the objectPointer array become
invalid when STL shifts the objects vector around in memory?

thanks!

Oliver
 
P

Peter Koch Larsen

laniik said:
Hi. I have a question. If I have a vector of objects and on of object
pointers:

---
vector <Obj> objects;
vector <Obj*> objectPointers;
---

and i setup the vectors with somhthing like:

---
Obj o;
objects.push_back(o);
objectPointers.push_back(&objects[objects.size()-1])
---

now. when i grow the objects array:

---
for(int i=0;i<10000;i++)
{
Obj o;
objects.push_back(o);
}
It is not only possible but almost guaranteed the way your code is written.

/Peter
 
R

Rolf Magnus

laniik said:
Hi. I have a question. If I have a vector of objects and on of object
pointers:

---
vector <Obj> objects;
vector <Obj*> objectPointers;
---

and i setup the vectors with somhthing like:

---
Obj o;
objects.push_back(o);
objectPointers.push_back(&objects[objects.size()-1])
objectPointers.push_back(&objects.back())

now. when i grow the objects array:

---
for(int i=0;i<10000;i++)
{
Obj o;
objects.push_back(o);
}

Yes. If objects reallocates its memory, all the pointers of objectPointers
will be invalidated.
One way to avoid that is by reserving space. In your example, put
objects.reserve(10000); before the loop. Then, enough memory for 10000
objects gets reserved, so as long as not more objects are added, the vector
will not reallocate.
Of course that is only an option if you know the size in advance.
Another solution is to not store pointers, but indexes. Those won't get
invalidated by push_back().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,007
Messages
2,570,266
Members
46,865
Latest member
AveryHamme

Latest Threads

Top