C++ 减少使用指针、原始指针或其他指针和/或返回可为空的非指针

C++ Reducing the use of pointers, raw or otherwise and/or returning nullable non-pointers

本文关键字:指针 返回 其他 C++ 原始      更新时间:2023-10-16

我正在使用OpenGL编写C++游戏,并决定编写一个基于组件的系统,非常类似于Unity或虚幻引擎 - 为了好玩并了解这些系统是如何制作/工作的。我已经到了需要实现组件和游戏对象的地步,我已经非常成功地完成了。

我的实施工作...它只是不完全是我想要的。目前,我将组件存储为指向组件的指针的私有向量,并在请求时返回组件。

例子:

GetComponent<MeshRenderer>(); //Returns "MeshRenderer" Component as MeshRenderer*
AddComponent(new MeshRenderer(mesh)); //Adds component to vector + returns MeshRenderer*

组件是抽象类,由诸如网格渲染器之类的组件扩展。

T *AddComponent(T *component)
{
    component->parent = this;
    m_components[typeid(T).name()] = component;
    bool pushLocation = true;
    for (unsigned int i = 0; i < m_component_locations.size(); i++)
        if (m_component_locations.at(i) == typeid(T).name())
            pushLocation = false;
    if(pushLocation)
        m_component_locations.push_back(typeid(T).name());
    return GetComponent<T>();
}

上图:My AddComponent(); 代码,用于添加组件 - 需要一个指向组件的指针...

std::unordered_map<std::string, Component*> m_components; //Holds the components
std::vector<std::string> m_component_locations; //Holds data on components, allows them to be indexed

上图:如何在 GameObject 类中存储组件,允许我按索引遍历它们

我对这种方法的问题是由于我如何实现我的 GetComponent() 函数。它返回指向组件的指针,如果不存在此类组件,则可能返回 nullptr。

T *GetComponent()
{
    if (m_components.count(typeid(T).name()) != 0)
    {
        return static_cast<T*>(m_components[typeid(T).name()]);
    }
    else
    {
        return nullptr;
    }
}

我在这里的问题是,由于返回指针,我可以调用 delete 并删除指针。这些是原始指针,但我已确保在销毁游戏对象时由程序处理它们,因此 - 希望(除非我不称职)不担心内存泄漏 - 但我宁愿返回引用,因为你不能在它们上调用"删除" - 以避免我可能犯的任何愚蠢错误。

我已经将变量设为私有,游戏对象处理组件的删除,我宁愿不允许自己由于无能或类似原因而删除某些内容。

我曾考虑过返回unique_ptr但我不确定该实现是否更可取。

(作为额外的说明,我确实需要 GetComponent() 函数来返回某种 null 或指示不存在这样的组件)

你减少使用原始指针的想法是正确的。我认为您必须查看EntityX库并注意事情是如何实现的。那里根本没有指针。

对于您的情况,您必须执行与EntityX相同的操作 - 使用指向组件的引用(而不是指针)创建类ComponentHandle。此类不管理组件的生命周期。它只是组件的一个接口。您还可以重载->运算符以访问组件中的成员。

祝C++和组件实体系统好运。