Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

c++ garbage values in vector of pointer

When I do:

for(i=0; i<size; i++){
    //create objectA here
    vectorA.push_back(objectA);
    pvectorA.push_back(&vectorA[i]);
}

some elements of pvectorA is garbage. However when I do:

for(i=0; i<size; i++){
    //create objectA here
    vectorA.push_back(objectA);

}
for(i=0; i<size; i++){
    pvectorA.push_back(&vectorA[i]);
}

Everything is okay. Why is it happens?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Read the documentation of std::vector::push_back

First the description:

Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.

This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

Then about validity of iterators:

If a reallocation happens, all iterators, pointers and references related to the container are invalidated.

So, when you add an object to the vector, all the pointers pointing to objects in that vector may become invalid - unless you've guaranteed that the vector has enough capacity with std::vector::reserve.

Invalid means that the pointer no longer points to a valid object and dereferencing it will have undefined behaviour.

In the latter code, you never add objects to the pointed-to vector after you've stored the pointers, so the pointers are valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...