Why Does Pushing Back Local Variable to Vector Works

256 views Asked by At

The C++ vector stores pointers to the values it stores (i.e. vector of ints will store pointers to ints). In the following code, int i is a local variable in the for loop. Once the for loop is finished, the int i variable should be deleted from memory. Therefore, the vector pointers should be pointing to some garbage place in memory.

I plugged this code into XCode, yet it prints "30313233" – the ints that should have been erased from memory.

Why does it do this?

int main(int argc, const char * argv[]) {
std::vector<int> vec;
for(int i = 30; i < 34; i++)
{
    vec.push_back(i);
}
cout << vec[0];
cout << vec[1];
cout << vec[2];
cout << vec[3];

}

3

There are 3 answers

3
Rakete1111 On BEST ANSWER

The C++ vector stores pointers to the values it stores

Nope, that's not true. Objects in C++ are truely objects, they aren't hidden references like in Java.1 In your example, you are pushing back i. What this means is that a copy of the object will get added to the vector, and not the variable itself.


1: Technically, it does store a pointer, but that pointer is to refer to the memory block where the array lies, where actual ints are stored. But that's an implementation detail that you shouldn't (at this point) be worried about.

1
eesiraed On

The vector stores a pointer to the block of memory where the objects are stored, not the individual objects. When you insert into a vector, the object is copied into that block of memory.

0
Pete Becker On

vector<int> stores values of type int. vector<int*> stores values of type int*, i.e., pointer to int.