简体   繁体   中英

C++ - Safety of accessing element of vector via pointers

In a C++ project of mine, I am using a vector to hold a bunch of struct s which hold a number of elements for a simple game (ie: tic-tac-toe, coordinates, x vs o , etc). ie:

struct gameMove
{
  int x;
  int y;
  int player;
  int order;
};

Every time during a single game, whenever a player makes a move (ie: places an x or o ), the information is stored in the vector via push_back() , to create an "undo" feature, which currently works as expected.

In some parts of my undo/redo logic, I am using functions which traverse the vector , find the appropriate element, and return a pointer directly to that element.

Is it safe, so long as I'm correctly managing the vector , access to it, NULL-ing out all the pointers that point to elements of the vector , or are there inherent risks? My concern is that if extend the game, which I plan to do (ie: use the same code for a chess game I'm working on), and that the vector gets too large and needs to be automagically re-allocated, the pointers will become invalid (ie: entire list is moved to a new contiguous block that can fit all the elements), or is there some type of smart-pointer interface to vector to accomplish the same thing?

Thank you.

You are correct to be concerned: If the vector needs to grow, the addresses in the vector will change (or if the vector shrinks, but most implementations of vector doesn't shrink without some effort from the programmer).

The immediately simple solution would be to return the index into the vector, instead of a pointer. That, as long as it's in range, will always be a valid way to find a particular element. [And instead of NULL you could use for example -1 or 0xDEAD ]

Have you considered using the std::stack or the std::list ? The stack especially could be appealing for simplifying the "undo" functionality you're looking for (since the last move will always be the top of the stack). But with the linked structure, you wouldn't need to worry so much about the indexing issue, though if you're tight on memory they may not be the best option...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM