Reputation: 23
I just create list of Coordi object as below inside of a functions. Coordi is class object which I defined.
list<Coordi> LstOfCoordi;
for (int i = 0; i < 10; ++i)
{
Coordi *tmp = new Coordi();
LstOfCoordi.push_back(tmp);
}
I want release the list and each objects to the system before program termination.
If each element of list should have to be released, how to handle it ? I tried to below codes to use delete each of them, but it made compile error.
for (int i = 0; i < 10; ++i)
{
myClass tmp = LstOfMyCalss.back();
delete &tmp;
LstOfMyClass.pop_back();
}
So, I am wondering deletion from the list is enough or not. At a glance with below codes, each element was allocated and they are not released properly when the list destroyed.
for (int i = 0; i < 10; ++i)
{
//myClass tmp = LstOfMyCalss.back();
//delete &tmp;
LstOfMyClass.pop_back();
}
Please let me know the best way to release all allocated objects.
Upvotes: 0
Views: 1509
Reputation: 2809
Edit: Sample code on creating list of objects using std::list.
class MyClass {
public:
std::list<Coordi> m_listCoordi;
}
//---creation of list of objects
for(int a = 0; a < numObjects; a++){
m_listCoordi.push_back(Coordi()); //note: no 'new' is used.
}
//---destroying list of objects
m_listCoordi.clear();
Sample code on creating list of pointer to objects using std::list.
class MyClass {
public:
std::list<Coordi*> m_listCoordi; //<---note: now list of pointer
}
//---creation of list of objects
for(int a = 0; a < numObjects; a++){
m_listCoordi.push_back(new Coordi());
}
//---destroying list of objects
for(int a = 0; a < numObjects; a++){
delete m_listCoordi[a]; //note: an item in m_listCoordi is already a pointer.
}
m_listCoordi.clear();
I apologized for a messy answer. I don't have much time to make it clean and more formal. I hope it helps anyway.
Prev answer:
If your list, say std::vector<YourClass*>
, the elements hold pointer values. It's your responsibility to allocate and deallocate memory block from that pointer values that you save in the list. Whatever your method of allocating/deallocating, it's up to you. Just make sure your code won't produce memory leaks.
//---deallocate all elements before clearing the list.
for(auto& pItem : LstOfMyClass){
//note: since LstOfMyClass is a list of pointer values, pItem is a pointer variable.
delete pItem;
}
//---clear the list.
LstOfMyClass.clear();
If objects in the LstOfMyClass
does not move around or the list does not grow or shrink, better use list of objects instead of list of pointer to objects. With this you don't have to worry about allocating and deallocating. The list will do it for you if the list variable is destroyed.
Upvotes: 2