How to delete vector elements created by new

class BED
{
....
};
int main()
{
BED * tbed;
tbed =new BED(...);

// push element into vector.
vector<BED> BEDList;
BEDList.push_back(*tbed);

// push pointer into vector.
vector<BED *> tBEDList;
tbed=new BED(...);
tBEDList.push_back(tbed);

return 0;
}

I want to know how to delete the new created elements in vectors, respectively.

Thanks!





1
2
3
4
5
6
BED * tbed;
tbed =new BED(...);

// push element into vector.
vector<BED> BEDList;
BEDList.push_back(*tbed);

Here BEDList will store a copy of the object pointed to by tbed. You don't have to delete the object in the vector but you have to delete the object pointed to by tbed by doing delete tbed;


1
2
3
4
// push pointer into vector.
vector<BED *> tBEDList;
tbed=new BED(...);
tBEDList.push_back(tbed);

Here you must make sure that you don't delete the objects before you are finished using them. In this case you only have one object so you can do exactly the same as before but if you have many element in the vector you probably want to loop through the elements and delete them.
1
2
3
4
for (std::size_t i = 0; i < tBEDList.size(); ++i)
{
	delete tBEDList[i];
}
Last edited on
According to the documentation, both the .pop_back() and .erase() member functions of vector will call the destructors for the elements which are removed, so you shouldn't have to delete them explicitly, though memory leak analyses like valgrind might still chastise you.

1
2
3
4
5
6
7
vector<BED*> tBEDList ;
tBEDList.push_back( new BED() ) ; // creates tBEDList[0]
tBEDList.push_back( new BED() ) ; // creates tBEDList[1]
tBEDList.push_back( new BED() ) ; // creates tBEDList[2]
tBEDList.pop_back() ; // destroys tBEDList[2]
tBEDList.erase( tBEDList.begin() ) ; // destroys tBEDList[0]
tBEDList.clear() ; // destroys what was tBEDList[1] but which would now be [0] after the .erase() 
zerobandwidth:Here the pointers are the elements so only the pointers will be removed. The objects that the pointers point will stay alive. That is why we need to call delete.
Last edited on
@Peter87: That is interesting. I will have to make note of that and maybe learn a thing or two. Thanks. *^_^*
Topic archived. No new replies allowed.