How to delete a non-dynamic object?

Oct 13, 2014 at 12:50pm
I tried googling this but only results for deleting objects created with the keyword "new" came up. I'm trying to loop through a vector of class objects and if that object matches a certain parameter, then delete that object (note, I'm using the word delete loosely, I know that's not that actual keyword I'm looking for). Would the object be completely removed from memory as soon as I removed it from the vector, or is there something else to be done?
Here is a sample:

1
2
3
4
5
6
7
8
9
10
std::vector<Object> objs

  AddObjectToVector(){
    Object obj;
    objs.push_back(obj);
  }

  RemoveObject(){
    //I need to 1) remove the object from the vector. 2) delete the object from memory. How?
  }
Oct 13, 2014 at 12:58pm
if you want to remove an element from the vector use erase

http://www.cplusplus.com/reference/vector/vector/erase/
Oct 13, 2014 at 1:54pm
1
2
3
4
5
6
7
  vector<int>vec;
  vec.push_back(10); //insert 10
  vec.push_back(20);

  vec.pop_back(); // remove last element (20)
  vec.clear(); // remove all element, capacity() unchanged.
  cout << vec.size(); // 0 
Last edited on Oct 13, 2014 at 2:04pm
Oct 13, 2014 at 2:19pm
You need to be more precise with your questions.
wh1t3crayon wrote:
Would the object be completely removed from memory as soon as I removed it from the vector
No
AlternativeReading wrote:
Would the object destructor called as soon as I removed it from the vector
Yes.
Vectors do not free memory immediately, as it can be reused later, when more items would be added to vector.
If for some reason you really need to decrease vector capacity, .shrink_to_fit() member function should suit you.
Oct 13, 2014 at 3:59pm
Thanks for the replies. I was curious if just erasing an object from a vector was bad practice or if something else needed to be done, but it seems to be fine.
Topic archived. No new replies allowed.