C++ 减少使用指针、原始指针或其他指针和/或返回可为空的非指针
C++ Reducing the use of pointers, raw or otherwise and/or returning nullable non-pointers
我正在使用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++和组件实体系统好运。
- 在 const 函数中通过引用和指针返回之间的区别
- 指向 std::unrodered_map 中元素的指针返回'Read access violation'
- 为什么要为指针返回类型返回一系列字符?
- Visual C 运行时:Malloc将指针返回到已经使用的内存(包含实际字符串)
- 将原始指针返回到智能指针
- 从函数中的指针返回对象,例如链接列表
- 将指针返回使用New创建的数组数组
- 查找并将指针返回向量中的对象
- 函数可以将指针返回其自己的类型
- 指针返回值的地址
- 为什么静态指针返回函数中有一个"静态"键?
- 从弱指针返回类型返回共享指针
- 如何将C++引用和指针返回转换为 C++/CLR
- 从指针返回对象时出现意外的析构函数调用
- 阵列指针返回垃圾
- (C )当在同一类中调用时,污点指针返回正确的值,而从MAIN调用时为0
- C 从指针返回到成员功能
- 在构造函数以外的任何其他位置访问相机时,我的相机指针返回 null
- 从取消引用的指针返回原始指针
- 指针返回