我目前正在制作一個小型“游戲引擎”。我想知道是否應該使用智能指標以及應該使用哪種型別。還是我只是為這個 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;
};
謝謝閱讀。
uj5u.com熱心網友回復:
第一件事。一般來說,早期失敗比晚期失敗更受歡迎。交付后的失敗是災難性的。最受歡迎的失敗形式是在編譯時。好的代碼試圖通過在編譯時斷言錯誤來防止運行時或邏輯錯誤。所以不要被編譯錯誤嚇到。接下來,您必須決定物件的生命周期及其所有權。原始指標的主要問題是含義的模糊性。原始指標是否暗示:
- 僅供參考
- 可選參考
- 擁有的資源
- 陣列開頭
- PIMPL
- ...
很難通過使用原始指標查看代碼來判斷,這是預期的。編碼程序中的混亂會導致各種邪惡(包括資源泄漏、雙重洗掉、釋放后使用......)。
另一方面,智能指標將指向物件的用例限制為非常具體的情況(來自上面的串列或其他)。此外,智能指標提供了物件生命周期的保證。標準庫為上述不同的用例提供了各種類(智能指標或其他)。
如果這些類都不適合特定用例,我寧愿定義一個包裝器來封裝指標并裝飾其行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490434.html
上一篇:空指標不計算為假
