Hello again!..
I'm trying to figure out how to delete pointers within a list. With vectors you can do it with a for loop since you can use square brackets []. However, you can't do that with lists:
#include <iostream>
#include <list>
class Object
{
public:
Object() = default;
~Object() = default;
void SetValue( int val )
{
mValue = val;
}
void PrintValue()
{
std::cout << this->mValue << std::endl;
}
private:
int mValue;
};
int main()
{
// list of objects
std::list<Object*> objList;
// Fill list
for( int i = 0; i < 50; i++ )
{
Object* obj = new Object();
obj->SetValue(i);
objList.push_back( obj );
}
}
After that I'm actually not sure how to even access items within that list, hence why I don't really know how to delete the pointers in it either. I've tried looking at some examples online, but there aren't many regarding lists, mostly vectors. However, in my program it's a little easier using lists.
Do you mean that you simply want to remove the pointers from the list?
Or do you want to free up the memory that those pointers are pointing to?
Clarity is important!
EDIT:
I'm actually not sure how to even access items within that list
Lists are designed to support sequential access, rather than random access. So, to access the elements of a list, you should iterate over the list to access each element in turn. You can do this explicitly using std::list::iterator, but it's easier to simply use a range-based for-loop:
1 2 3 4
for (Object* obj : objList)
{
obj->PrintValue();
}
Note that using .erase()/.pop_back()/,pop_front() for a list of type pointer does call the destructor of the removed element. If the list is memory owning (as opposed to memory reference), then before an item from the list is removed, the destructor for the item needs to be used via delete.
Thanks a lot for your answers. I actually did make my list store unique pointers. I still need to learn more about lists but you've pointed me in the right direction, thank you!
It's not resizeable, but the size of a managed pointer array can certainly be specified at run-time. They're really just a RAII for new/delete. Consider: