c++ - How to delete same pointer in different std::vector's? -
c++ - How to delete same pointer in different std::vector's? -
my game's main loop looks this:
std::vector<std::unique_ptr<state>> states; for(size_t = 0; < states.size(); i++) { states[i]->update(); states[i]->draw(); } their flaw though. can't modify vector (delete state) during iteration because if deleted current state iteration on breaks because there no state phone call update , draw on. thought thought create vector of states should added states vector , create vector of states should deleted states vector. after loop on modify states vector , no problems occur mid iteration.
std::vector<std::unique_ptr<state>> states; std::vector<std::unique_ptr<state>> statestobeadded; std::vector<std::unique_ptr<state>> statestoberemoved; for(size_t = 0; < states.size(); i++) { states[i]->update(); states[i]->draw(); } for(size_t = 0; < statestobeadded.size(); i++) { states.push_back(std::move(statestobeadded[i])); } statestobeadded.clear(); for(size_t = 0; < statestoberemoved.size(); i++) { states.erase(std::remove(states.begin(), states.end(), statestoberemoved[i]), states.end()); } statestoberemoved.clear(); //error thrown here i can't delete states states vector though, error thrown on statestoberemoved.clear() line , think it's because when phone call states.erase(...) line deletes element states vector consequently nullifies same element in statestoberemoved vector since element points object no longer exists.
you can't delete std::unique_ptr without destroying pointer points don't think there way delete element states vector without nullifying element in statestoberemoved vector. how solve problem?
thanks.
different pointer types cater different ownership semantics:
unique_ptrs unique ownership, why current code not work shared_ptrs shared ownership - when lastly shared_ptr managing object goes out of scope, destroyed raw pointers (*) don't semantics modeling, have enforce constraints manually - that's makes them dangerous. however, safe, (and in sentiment sensible choice) pointers never have ownership of object pointed to. so: statestobeadded safe long can guarantee never have in there isn't in states. statestoberemoved different: objects there , in states, , create sense have states take ownership of objects - hence raw pointers fair selection statestoberemoved.
note based on few lines of code have shown, depending on circumstances may makes sense store states instead of unique_ptr<state>s in states, etc ...
c++ pointers stdvector game-loop
Comments
Post a Comment