c++memoryvectorstdvectordynamic-allocation

Why Does Pushing Back Local Variable to Vector Works


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];

}


Solution

  • 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.