I am working on a simple game for which i need to store the game-objects in containers. I want to store them in different std::list (objects that get drawn to the screen every frame, objects that need to be updated every frame, etc) so i can just iterate over all objects of a certain type when i need it. Now some objects have to be in more than one list (some of them get drawn and need to be updated every frame) and sometimes it is necessary to delete one from all lists that contain it. The objects should get deleted when they are removed from all lists. This is a simplified example of what i currently have:
#include <iostream>
#include <memory>
#include <string>
#include <list>
class A
{
public:
A(std::string text)
{
message = text;
}
~A()
{
std::cout << "Deleted: " << message << std::endl;
}
std::string getMessage() { return message; }
private:
std::string message;
};
int main()
{
std::list<std::shared_ptr<A>> list1;
std::list<std::shared_ptr<A>> list2;
if(true) // to create scope
{
std::shared_ptr<A> tmp(new A("Test"));
list1.push_back(std::shared_ptr<A>(tmp));
list2.push_back(std::shared_ptr<A>(tmp));
} // tmp out of scope
// delete the object from both lists:
auto i = std::begin(list1);
while(i != std::end(list1))
{
if(i->get()->getMessage() == "Test");
list1.remove(*i);
list2.remove(*i); // the object gets deleted after this line
}
return 0;
}
It work's but it really seems overly complicated (i'm using C# at work where this task is trivial). I have very little experience with memory management using smart pointers. Am i doing something fundamentally wrong?