How to automatically maintain a list of class instances?

In my C++ project, I have an Engine class and an Object class.

My issue lies with how my instances of Object are created. Currently this is done through the use of a CreateObject(parameters) function in the Engine class. This adds a new instance of Object to an std::vector of Object instances.

I want to maintain this list of instances of Object in my Engine class, but without the need for the CreateObject(parameters) function. My reason for this is so that I can create new classes that can inherit from Object but still be added to this list. The reason for this list is so that (in Engine) I can iterate through every Object instance that has been created.

This would ultimately mean that I create my Object instances with something like Object newObject = Object(parameters);, but still have the Engine class maintain a list of all Object instances, without the need for Object to reference the instance of Engine or the list to add itself to this list (as in the instance of Object should not know about the list it is in). Can this be done?

Answers


You can define a static collection data member in your Engine class, update it in your Object constructor and destructor:

class Engine
{
    friend class Object;
...
public:
    static std::set< Object* > m_instances;
};

class Object
{
public:
    Object();
    virtual ~Object();
    ...
};

You increment it in constructors, and decrement it in destructors.

Object::Object()
{
    Engine::m_instances.insert(this);
}

Object::~Object()
{
    Engine::m_instances.erase(this);
}

Need Your Help

CUDA Dynamic Parallelism debugging is not supported in preemption mode. Breakpoints will be disabled

c++ debugging visual-studio-2012 cuda nsight

Now, I realize there is already a "solution" to this problem, but that solution doesn't work for me.

Can you register a Web API ActionFilter without doing it globally?

c# asp.net-web-api

I have seen how to do this globally in numerous posts and have it working in my code. The problem is that it's firing on EVERY call which isn't what I want, I only want it to fire on the calls to ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.