我目前正在制作一个小型“游戏引擎”。我想知道是否应该使用智能指针以及应该使用哪种类型。还是我只是为这个 GameObject 类使用原始指针。GameObject 的每个实例都附加了组件变换、精灵等。我应该使用智能指针还是只使用原始指针。因为我从来没有使用过智能指针,当我尝试使用时我总是会遇到一堆错误。使用原始指针可以吗?
游戏对象.h:
class Component;
class GameObject{
public:
GameObject();
virtual ~GameObject();
void addComponent(Component* component);
//return the first component of type T
template<typename T>
T* getComponent(){
for(auto component : components){
if(dynamic_cast<T*>(component)){
return dynamic_cast<T*>(component);
}
}
}
// return the component with the type T
template<typename T>
std::vector<T*> getComponents(){
std::vector<T*> components;
for(auto component : this->components){
if(dynamic_cast<T*>(component)){
components.push_back(dynamic_cast<T*>(component));
}
}
return components;
}
void removeComponent(Component* component);
std::vector<Component*> components;
};
//======================================================
class Component
{
private:
public:
Component();
virtual ~Component();
//the game object this component is attached to
GameObject* gameObject;
};
谢谢阅读。
第一件事。一般来说,早期失败比晚期失败更受欢迎。交付后的失败是灾难性的。最受欢迎的失败形式是在编译时。好的代码试图通过在编译时断言错误来防止运行时或逻辑错误。所以不要被编译错误吓到。接下来,您必须决定对象的生命周期及其所有权。原始指针的主要问题是含义的模糊性。原始指针是否暗示:
很难通过使用原始指针查看代码来判断,这是预期的。编码过程中的混乱会导致各种邪恶(包括资源泄漏、双重删除、释放后使用......)。
另一方面,智能指针将指向对象的用例限制为非常具体的情况(来自上面的列表或其他)。此外,智能指针提供了对象生命周期的保证。标准库为上述不同的用例提供了各种类(智能指针或其他)。
如果这些类都不适合特定用例,我宁愿定义一个包装器来封装指针并装饰其行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句