C++ |数组、向量、集合等中不具有多态性的不同类型元素的分组

发布于 2025-01-09 04:12:42 字数 908 浏览 1 评论 0原文

我有一个存储组件的类(有点像视频游戏中的“实体组件系统”):

class Components
{
public:
   
    template <typename T>
    T& AddComponent()
    {
        T* component = new T();
        m_Components.push_back(component);
        return *component;
    }

    //... More Templated code to use the stored components and delete allocated memory

private:
    std::vector<void*> m_Components;
}

我知道这在某种程度上有效,因为我测试了很多次。

我想知道的是,如果有其他方法可以实现相同的目的,不使用多态性,那可能会更安全?

另外,如果我想删除内存,是否可以在可能指向许多不同类型的 void* 上调用 delete

编辑: 如果我必须使用多态性,我会的,但它只是一个没有数据的空类。

问题是,我的 Components 类的每个实例并不总是具有相同数量的组件。想象一下,我有许多具有不同行为的不同组件,例如“AudioComponent”、“RenderComponent”等。

有时此类的实例只有一个或两个组件,而其他时候它会有更多内容,这就是为什么对我来说将其保存在某种类型的动态数组中是有意义的。

如果有任何其他方法可以完成类似的事情,请指出我的方向。

I have a class that stores components (a little bit like how an "Entity Component System" in a videogame would) as such:

class Components
{
public:
   
    template <typename T>
    T& AddComponent()
    {
        T* component = new T();
        m_Components.push_back(component);
        return *component;
    }

    //... More Templated code to use the stored components and delete allocated memory

private:
    std::vector<void*> m_Components;
}

I know this works to a point, because I tested it many times.

What I want to know is, if there are any other ways of accomplishing the same, without using polymorphism, that might be safer?

Also, if I want to delete the memory, is it OK to just call delete on a void* that could be pointing to many different types?

Edit:
If I have to use polymorphism I will but it would only be an empty class with no data.

The thing is not every instance of my Components class will not always have the same number of components. Imagine I have many different components with different behaviour like 'AudioComponent', 'RenderComponent', etc.

Sometimes an instance of this class will have only one or two components and other times it will have a lot more which is why it makes sense to me to save it in some type of dynamic array.

If there is any other way to accomplish something like this please point me to that direction.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文