0

The below code works during release mode and raising an error at g_ItemList.push_back() during debug mode only, I went through few SO posts and forums. Somebody mentioned "You can't iterate through a vector while pushing back, as push_back may invalidate iterators". But it's not clear for me. Could somebody explain the logic behind it and How to fix this? I am using Visual Studio 2010 (v100) to compile the program

std::vector<class PPart> VECT_ITEMS;    
VECT_ITEMS g_ItemList;
g_ItemList.clear();

for (i = 0; i < n; i++)
    g_ItemList.push_back (temp[i]);     //where PPart *temp;

Error Message enter image description here

RobinAtTech
  • 1,299
  • 3
  • 22
  • 48

1 Answers1

2

A vector is essentially a wrapper around an array. The given array has a particular size, and the vector's data is stored as the first n elements of this array, where n is the size of the vector and the size of the array is greater than or equal to n. When you call push_back and the vector does not have enough space in its internal array, it creates a new one of a greater size (often double the now-insufficiently-sized array) and copies all of the vectors elements into that array before deleting the old one (these arrays are stored on the heap and created via new and delete).

Iterators are essentially pointers into this internal array¹. As such, when you call push_back, all current iterators may be invalidated. This is because a new array may have been created, and pointers into the old array refer to now-freed memory. Technically, when you call push_back and then dereference an iterator that was created before that call, it is undefined behavior.

1: Technically, they are class wrappers of pointers to the internal array, but the principle stands either way. It is often, but not always, useful to think of them as just pointers.

john01dav
  • 1,842
  • 1
  • 21
  • 40
  • So there are no ways to fix this error in debug mode? – RobinAtTech May 27 '19 at 01:20
  • 2
    @RobinAtTech It would be useful for you to read the link that I gave about undefined behavior as it isn't safe even in release mode. It is most likely to arbitrarily quit working some day with a compiler update, compiler switch, windows update, or any number of other things. Also, I just re-read your code and looks like I minorly misunderstood it because it is note an [MCVE](https://stackoverflow.com/help/minimal-reproducible-example). Can you post one please? – john01dav May 27 '19 at 01:53