using an std::vector of std::unique_ptr
using an std::vector of std::unique_ptr
我是使用智能指针的新手,到目前为止只使用过unique_ptr
。我正在创建一款游戏,我使用vector
或unique_ptr
来存储我的游戏状态。
这是我的矢量代码:
std::vector<std::unique_ptr<GameState>> gameStates;
这是我的问题。下面的函数可以用来控制向量吗?
void GameStateManager::popGameState(){
if (getCurrentGameState() != nullptr)
gameStates.pop_back();
}
void GameStateManager::pushGameState(GameState *gameState){
gameStates.push_back(std::unique_ptr<GameState>(gameState));
}
GameState *GameStateManager::getCurrentGameState(){
return gameStates.back().get();
}
我担心使用原始指针作为参数并返回当前游戏状态会消除使用智能指针的意义。这是一个好方法吗?
试试这个:
void GameStateManager::pushGameState(std::unique_ptr<GameState> gameState){
gameStates.push_back(std::move(gameState));
}
std::unique_ptr
不能复制,但可以移动。
我认为它有一些好处…请看下面的代码:
std::unique_ptr<GameState> pgs;
...
gsm.pushGameState(pgs); // error!
gsm.pushGameState(std::move(pgs)); // you should explicitly move it
如果使用原始指针…,
void GameStateManager::pushGameState(GameState *gameState) { ... }
{
std::unique_ptr<GameState> pgs;
...
gsm.pushGameState(pgs.get()); // IT'S NOT COMPILE ERROR! you can make some mistakes like this..
gsm.pushGameState(pgs.release()); // you can use it, but I think you will make a mistake sometime, finally.
} // if you use `pgs.get()`, the `GameState` is deleted here, though `gameStates` still contains it.
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- 引用 std::shared:ptr 以避免引用计数
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 使用std :: String ptr的错误打印std :: String
- C++中的大小释放:全局运算符delete的正确行为是什么(void*ptr,std::size_t size)
- std::哈希表示无序映射中的唯一 PTR
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- 正确使用std智能指针以确保ptr安全
- 如何创建 std::string 包装器,它将 ptr 保留为 std::string 和 ptr 到创建该包装器实例的
- 为什么 std::string{ "const char ptr" } 有效?
- 为什么 gcc 4.9.0 中没有定义"void operator delete(void* ptr, std::size_t size) noexcept;"?
- 在 std::map 的值中使用非 ptr 是一种很好的做法吗
- 共享 PTR - C++:std::shared_ptr<T> 和 std::shared_ptr<T const> 有什么区别?