-2

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

}

Y. Moondhra
  • 195
  • 2
  • 12

3 Answers3

2

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.

eesiraed
  • 4,626
  • 4
  • 16
  • 34
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • So it (1) makes a copy of the object and then (2) stores a pointer to that copy of the object in memory? (At this point) I would like to know the full info as I am applying to internships – Y. Moondhra Aug 17 '18 at 04:35
  • @Y.Moondhra 1) yes, 2) no. The vector has a block of memory. When you use `push_back`, the vector creates a new object into that block of memory, which copies the object you passed into the new object being created. The only pointer it stores is to the start of the block of memory (like `int a[] = {1, 2}; int *b = a;`, `b` is a pointer to the block of memory of the array). – Rakete1111 Aug 17 '18 at 04:47
  • Now I completely understand it. Thank you. – Y. Moondhra Aug 17 '18 at 04:52
1

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.

eesiraed
  • 4,626
  • 4
  • 16
  • 34
0

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

Pete Becker
  • 74,985
  • 8
  • 76
  • 165