Under what condition will this pointer be invalidated? About a vector of class object which has vector members.

I have a class like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class a {
public:
    std::vector<int> v;
    a * prev, * next;//this pointers gonna point to its neighbor
}

//now I use it like this:

std::vector<a> a1;

//I just want to know which of the following operations will make prev and next invalid

a1.resize(newNumber);
a1.v.resize(newNumber);

//what if I do the following firstly
a1.reserve(aNumber);
a1.v.reserve(aNumber);

//and then do the following
a1.resize(newNumber);//if newNumber<=aNumber? if newNumber>aNumber?
a1.v.resize(newNumber);//if newNumber<=aNumber? if newNumber>aNumber? 


Right now, I am guessing only the operation of a1.resize() will make prev and next invalid, because v is only stored as a pointer in class a. If v is resized only, v will be allocated to new place, that pointer stored in class a is changed, but the memory to store this pointer is constant.

Am I right? Is there any other operations I should be careful?
Last edited on
You are right; the class a objects have a fixed size. The member object v of a has fixed size, because the actual data hold by std::vector is not within the object v.

The a1 is a vector. pointers and iterators to its elements are invalidated by ... it is better that you check the reference documentation for at least each std::vector operation that you will use, because they do state whether invalidation can occur.

Vector has capacity -- how much space it has allocated -- and size -- how much of that allocated space is in use. Reallocation is forced whenever the new size would exceed the current capacity.

Note, that non-tail insert() and erase() invalidate some iterators even without reallocation.
Thank you!
Topic archived. No new replies allowed.