Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 structs 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.

like image 561
Cloud Avatar asked Jan 08 '23 21:01

Cloud


2 Answers

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]

like image 163
Mats Petersson Avatar answered Jan 10 '23 09:01

Mats Petersson


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...

like image 34
Tyler Avatar answered Jan 10 '23 11:01

Tyler