如何自动维护类实例的列表? [英] How to automatically maintain a list of class instances?

查看:163
本文介绍了如何自动维护类实例的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C ++项目中,我有一个 Engine 类和 Object 类。

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

我的问题在于如何创建 Object 的实例。目前这是通过在 Engine 类中使用 CreateObject(parameters)函数来完成的。这向对象 std :: vector 添加了 Object 的新实例c $ c>实例。

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.

我想维护 Object c> Engine 类,但不需要 CreateObject(parameters)函数。我的原因是,我可以创建可以从 Object 继承但仍然添加到此列表的新类。这个列表的原因是(在 Engine ),我可以遍历已经创建的每个 Object 实例。

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.

这最终意味着我创建了 Object 实例,例如 Object newObject =对象(参数); ,但仍然有 Engine 类保留所有 Object 实例,而不需要 Object 引用 Engine 的实例或将列表添加到此列表如 Object 的实例不应该知道它所在的列表)。

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?

推荐答案

您可以在Engine类中定义静态集合数据成员,在你的Object构造函数和析构函数中更新它:

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);
}

这篇关于如何自动维护类实例的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆