Vectors and memory

I’ve read the tutorial, searched the internet, but still can’t find a satisfactory answer.

If I have

  
vector<Tile> list;  

Then am I okay to populate it like this?

  
  
if(keyDown == 'x'){  
    Tile temp;  
    list.push_back(temp);  
}  
  

Or do I have to delete temp? Or does the block delete temp? I tried making a “new Tile” but that didn’t work.

I don’t really understand .erase either. Is that deleting the objects? Or do I have to do that? (I know I have to do that with a vector of pointers - but I don’t even know if I’m deleting just the pointers or the objects.)

I’m basically not getting a clear idea from any tutorial I’ve seen on what gets deleted as a standard and what I have to manually delete. I assume basic datatypes are cleaned up but I’m not sure about pointers to basic datatypes.

If you declare a variable as a non pointer then it’ll get deleted automatically when it goes out of scope, the scope it’s delimited by the { } in which it’s enclosed or if it’s a class member then when that class is destroyed.

Same applies for vectors, if you put objects in them then they’ll get deleted when they are removed from the vector with erase, clear or when the vector is destroyed.

Also in your example when you call push_back you are actually making a copy of the object so modifying the original won’t have any effect on the copy in the vector

if you want to understand this better look for stack vs heap memory allocation

Thanks, this is a bit clearer.

I’m concerned about the following code however:

  
void Grid::split(int x, int y){  
    xAxes.clear();  
    yAxes.clear();  
    int step, i;  
      
    step = width / x;  
    for (i = 0; i < width; i += step) {  
        xAxes.push_back(Interval(X_AXIS, i));  
    }  
    step = height / y;  
    for (i = 0; i < height; i += step) {  
        yAxes.push_back(Interval(Y_AXIS, i));  
    }  
}  
  

This creates a grid for me. Should I be declaring new Intervals or is it fine as it is? The code appears to run fine. But what would be the difference?

yes that’s ok, actually using new Interval can be sometimes slower since the allocated memory is not contiguous