Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...