Thursday, December 18, 2008

Dont make a pointer to vector members

It's very dangerous to make a pointer to member of vector. That's because if you add or move a member from vector, then all the reference or pointer to this vector will become invalidate.

If you want to keep the address of the member , a good way is to allocate memory for every member using "new". The vector just save the pointers to the address of these members. Don't forget to "delete " all members if you don't use this vector anymore.

An example:
vector vec;
for(int i=0;i<3;i++) { int * a =new int; *a=i; vec.push_back(a); }
for(int i=0;i{
delete vec[i];

No comments: