Let's say I have this simple code:
std::list<Class*> mList
mList.insert(mList.begin(), new Class())
Do I need to worry about manually disallocating the new Class element or is it taken care of by List if I use erase()?
Let's say I have this simple code:
std::list<Class*> mList
mList.insert(mList.begin(), new Class())
Do I need to worry about manually disallocating the new Class element or is it taken care of by List if I use erase()?
You created it, you need to destroy it.
My advice would be to avoid this if possible (and it usually is). Either put values in the list (usually preferable) or consider using a boost::ptr_list
. Or, you might consider something like a std::list<std::unique_ptr<Class>>
.
Note that there are substantial differences between std::list
and std::vector
with respect to the decisions you need to make here. Just for one really obvious example, in a vector
, you need to plan for the fact that objects in the collection will be copied/moved as the collection grows. That can rule out storing objects in some cases. With a std::list
, however, no copying/moving is ever needed or done. Each node in the list is allocated individually, and once it's allocated it won't be copied or moved. In fact, this is one of the biggest reasons to use a list in the first place.
So, even if your Class
defines an identity object that can never be copied or moved, it's still perfectly fine to store it by value in a list (even though you couldn't do the same in a vector
).
Yes, in this example, you will have to delete
all elements of the list after they are removed from the list, or before list is destroyed.
This is why you should rather use std::unique_ptr
- this will ensure it happens automatically.
Use smart pointers and it will release the memory as appropriate.
#include <memory>
https://www.google.com/amp/s/www.geeksforgeeks.org/smart-pointers-cpp/amp/