c – 如何将原始指针的矢量转换为唯一指针的矢量?
作者:互联网
#include <vector>
enum ListOfGameStates
{
// List of game states
};
class GameState()
{
public:
GameStates(); // Initializes protected (global) variables
virtual ListOfGameStates run() = 0;
protected:
// Heavyweigh resource managers containing all resources and other global vars
}
class GameStateManager()
{
public:
GameStateManager(); // Creates all game states
~GameStateManager(); // Deletes all game states
void run(); // Switches from one state to another state
private:
// A vector of raw pointers to game states. GameState is a base class.
std::vector<GameState*> game_states_container;
}
我想摆脱原始指针,这样我就不用担心异常和清理了.有一个简单的简单解决方案(我是一个非常愚蠢的青少年)或者它不值得吗?谢谢!
解决方法:
只需将矢量更改为:
std::vector<std::unique_ptr<GameState>> game_states_container;
并删除析构函数中的任何删除.事实上,除非有其他工作要做,否则你可以完全摆脱析构函数.
unique_ptr是不可复制的,但它是可移动的,因此值得对C 11移动语义有所了解.如果要向容器中添加unique_ptr,可以使用push_back,只需传递一个临时值,例如函数的返回值:
game_states_container.push_back(createGameState());
game_states_container.push_back(std::make_unique<GameStateA>()); // C++14
或者,如果您有本地unique_ptr变量,则可以使用std :: move将其移动到向量中:
std::unique_ptr<GameState> game_state = std::make_unique<GameStateA>(); // C++14
// auto game_state = std::unique_ptr<GameState>(new GameStateA); // C++11
...
game_states_container.push_back(std::move(game_state));
最好在新的时候将原始指针放在unique_ptr中(或者最好使用std :: make_unique).否则,如果在unique_ptr中分配和换行之间抛出异常,则会发生内存泄漏.
它与unique_ptr无关,但与GameState类should have a virtual destructor无关.
标签:raii,c,smart-pointers,raw-pointer 来源: https://codeday.me/bug/20190725/1528758.html