我目前正在研究2D遊戲引擎,並且已經閱讀過有關auto_ptr的內容,以及您應該如何將它們放在標準容器中。auto_ptr和容器 - C++
我的引擎具有這樣的結構:
StateManager - 有很多 - >國。
在引擎之外的主體中創建和分配狀態。我希望引擎存儲所有狀態的列表/矢量,以便在命令之間切換它們。
例如:
SomeState *test = new SomeState();
StateManager->registerState(test);
Since states die when and only when the application dies, can I use this approach?
std::auto_ptr<SomeState> test(new SomeState()); StateManager->registerState(test.get());
// Inside StateManager State *activeState; // State manager then maintains a vector std::vector<State*> stateList; // and upon registerState it adds the pointer to the vector void registerState(State *state) { stateList.push_back(test); }
The StateManager should only maintain a vector of pointers to the states, it shouldn't need to take ownership. When I want to change state in the engine, I just change the activeState pointer to point to the desired state which is found in the stateList vector.
Is this a bad approach?
+1用於Boost指針容器。 – mskfisher 2010-07-13 11:55:10
當使用boost容器時,是否將auto_ptr按原樣傳遞給registerState()並將參數類型更改爲std :: auto_ptr,還是仍然使用.get()函數傳遞它? – John 2010-07-13 12:03:35
您不要在boost :: ptr_vector中使用auto_ptrs。您只需將它交給一個裸指針,並且ptr_vector獲得它的所有權。 – Ferruccio 2010-07-13 12:07:33