patterncppMinor
Creating objects and putting them into std::list
Viewed 0 times
stdobjectscreatingintoputtingandlistthem
Problem
I am writing small roguelike game where I spawn some items and put them into the
The
Somewhere in the code I also defined:
Now I am using this code to create an item:
At the end of the program I use small loop to delete all items:
Is this approach for creating objects, putting them in
at the end deleting them correct, or am I missing something important here?
std::list. Is this the right way to do it?The
Item class is as followed (I know it has public id property):class Item {
public:
Item();
~Item();
unsigned int id;
};Somewhere in the code I also defined:
list listOfItems;
list::iterator it;Now I am using this code to create an item:
Item *p = new Item();
p->id = itemCrowbar;
listOfItems.push_back(p);At the end of the program I use small loop to delete all items:
for (it = listOfItems.begin(); it!=listOfItems.end(); it++) {
delete *it;
}Is this approach for creating objects, putting them in
std::list andat the end deleting them correct, or am I missing something important here?
Solution
If
If
In that case, you won't need to delete
However, if
Or you can create a list of 'smart pointers' (
Item has subclasses, then make the ~Item() destructor virtual.If
Item has a copy constructor, and is not a superclass of a subclass, then you can store a copy of the item (not pointer to the item) in the list:list listOfItems;
Item item;
item.id = itemCrowbar;
listOfItems.push_back(item);In that case, you won't need to delete
Item pointers before the list is destroyed.However, if
Item has subclasses, then this might be legal but a bug (called 'object slicing'):list listOfItems;
SubclassOfItem item;
item.id = itemCrowbar;
item.extra = "hello";
listOfItems.push_back(item);Or you can create a list of 'smart pointers' (
std::unique_ptr) to items: which behave like pointers to Items except that you don't need to delete the Item (the Item is deleted when the smart pointer which contains it is destroyed).Code Snippets
list<Item> listOfItems;
Item item;
item.id = itemCrowbar;
listOfItems.push_back(item);list<Item> listOfItems;
SubclassOfItem item;
item.id = itemCrowbar;
item.extra = "hello";
listOfItems.push_back(item);Context
StackExchange Code Review Q#41525, answer score: 6
Revisions (0)
No revisions yet.